[英]React with Semantic UI, Dynamically Add Props
Semantic-UI有这个React组件,我正在使用Segment 。
在我的应用程序中,我使用带有Segment的onMouseOver,如下所示:
render() {
return (
<Segment onMouseOver={this.handleHover} />
);
}
我想handleHover()要做的是动态地将语义UI道具添加到鼠标悬停事件的Segment上。 我尝试使用react clone元素执行此操作,并根据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 Component,当我将鼠标悬停在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
,并且当调用onMouseOver
回调时, Segment
组件将获得新的prop。
您可以根据您的示例将
propName
更改为color
,将this.state.propValue
为'teal'
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.