Reactjs 从父组件网中的事件更改子组件网中的样式
我有一个react组件,其中包含两个子组件,在父组件中我有一个按钮,它启动一个函数来更改父组件和子组件中的样式。 我成功地改变了父对象的样式,但没有改变子对象的样式 这就是我所做的Reactjs 从父组件网中的事件更改子组件网中的样式,reactjs,Reactjs,我有一个react组件,其中包含两个子组件,在父组件中我有一个按钮,它启动一个函数来更改父组件和子组件中的样式。 我成功地改变了父对象的样式,但没有改变子对象的样式 这就是我所做的 var XBlockButtons = React.createClass({ getInitialState(){ return{ Componentstyle:{display:"block"}, HTMLstyle:{display:"none"}, } }, showhtml(){ this.
var XBlockButtons = React.createClass({
getInitialState(){
return{
Componentstyle:{display:"block"},
HTMLstyle:{display:"none"},
}
},
showhtml(){
this.setState({
Componentstyle:{display:"none"},
HTMLstyle:{display:"block"}
})
},
render: function() {
var style={display:'block'}
return (
<div className="add-xblock-component new-component-item adding">
<div className="new-component" style={this.state.Componentstyle}>
<ul className="new-component-type" >
<li>
<button type="button" className="multiple-templates add-xblock-component-button" data-type="html" onClick={this.showhtml}>
<span className="large-template-icon large-html-icon"></span>
<span className="sr"> Add Component:</span>
<span className="name">HTML</span>
</button>
</li> /ul></div>
<HTML/>
---孩子---
这是因为您还需要将样式值作为道具传递给子组件
<HTML {...HTMLstyle}/>
我可能在语法上错了,但我希望你能理解。将样式作为道具传递给子组件,然后像这样使用它 家长:
<HTML HTMLstyle={this.state.HTMLstyle}/>
现在是孩子
var HTML = React.createClass({
componentWillMount: function(){
this.setState({HTMLstyle: this.props.HTMLstyle})
},
componentWillReceiveProps: function(nextProps) {
this.setState({HTMLstyle: nextProps.HTMLstyle})
},
render:function(){
return(
<div className="new-component-templates new-component-html" style={this.state.HTMLstyle}></div>
);
}
)};
感谢您的回答,它工作得很好,但是我不明白为什么会使用componentWillMount和ComponentWiilReceiveProposo每次父组件渲染时都会调用ComponentWillReceiveProps,而不是在子组件第一次渲染时,因此,对于第一次渲染,我们使用componentWillMount,对于任何进一步的渲染,我们使用ComponentWillReceivePropson还有一个问题,如果我必须反转过程,如果我必须将样式从子级传递到父级,我需要更改什么?有关反转方法,请参阅此
var HTML = React.createClass({
componentWillMount: function(){
this.setState({HTMLstyle: this.props.HTMLstyle})
},
componentWillReceiveProps: function(nextProps) {
this.setState({HTMLstyle: nextProps.HTMLstyle})
},
render:function(){
return(
<div className="new-component-templates new-component-html" style={this.state.HTMLstyle}></div>
);
}
)};