React with Semantic UI, 动态添加 Props

React with Semantic UI, Dynamically Add Props

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

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

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

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

添加了一个新的颜色道具

React 文档状态:

Clone and return a new React element using element as the starting point. The resulting element will have the original element's props with the new props merged in shallowly.

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

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

所以即使在克隆 React 组件之后,当我将鼠标悬停在 Segment 上时它仍然没有显示新的颜色属性。

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

您可以将任何您想要的 prop 值添加到当前组件的状态,并更改该值 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 回调获取时获得新的 prop打电话。

You can change propName to color and this.state.propValue to 'teal', based on your example.