1

Semantic-UI 有这个 React 组件,我正在使用的Segment 。

在我的应用程序中,我将 onMouseOver 与 Segment 一起使用,如下所示:

render() {
    return (
      <Segment onMouseOver={this.handleHover} />
    );
  }

我想要 handleHover() 做的是在鼠标悬停事件上动态地将语义 UI 道具添加到 Segment。我尝试使用react clone element执行此操作,并根据 Semantic UI 文档添加新的颜色道具

反应文档状态:

使用 element 作为起点克隆并返回一个新的 React 元素。结果元素将具有原始元素的道具和新道具的浅层合并。

handleHover() {
    React.cloneElement(Segment, {
      color: "teal"                  //NEWLY ADDED
    });

    //THIS EXECUTES SO EVENT IS TRIGGERING.
    console.log("I'm in here");
  }

因此,即使在克隆了 React 组件之后,当我将鼠标悬停在 Segment 上时,它仍然不会显示新的颜色属性。

问题:这是动态添加道具的正确方法吗?如果是这样,那么为什么不显示新添加的颜色。如果没有,那么我应该如何更改我的代码?

4

1 回答 1

3

您可以将所需的任何道具值添加到当前组件的状态,并更改该值onMouseOver

constructor(props) {
  super(props);

  this.state = {
    propValue: undefined
  }
  this.handleHover = this.handleHover.bind(this);
}

handleHover(event) {
  this.setState({propValue: 'hover'});
}

render() {
  return (
    <Segment onMouseOver={this.handleHover} propName={this.state.propValue} />
  );
}

的值this.state.propValue将从undefined变为hover,并且当回调被调用Segment时,组件将获得该新道具。onMouseOver

根据您的示例,您可以更改propNamecolor和。this.state.propValue'teal'

于 2017-08-21T23:46:13.037 回答