【发布时间】:2018-01-21 21:49:51
【问题描述】:
在反应中,假设我有输入组件,道具名称 = A、B、C。 它们按顺序呈现
render() {
return(
<Input name="A" />
<Input name="B" />
<Input name="C" />
);
}
然后我按照先的顺序改变C和A的状态C 然后 A. 组件 A 和 C 以先渲染的顺序重新渲染 A 然后是 C。它们不是按状态变化的顺序呈现的(C 然后 A)
参见下面给出的代码 sn-p。 我发现输出为
设置C的状态
设置B的状态
设置A的状态
A 的渲染
B 的渲染
C 的渲染
class Input extends React.Component { componentWillMount() { this.props.addInput(this); } state = { error: false } check() { console.log("set state of", this.props.name) this.setState({ error: true }) } render() { console.log("Render of", this.props.name) return ( <input /> ); } } class Hello extends React.Component { constructor(props) { super(props); this.inputs = {}; } addInput(component) { this.inputs[component.props.name] = component; console.log(this.inputs); } checkAll() { const inputs = this.inputs; Object.keys(inputs).reverse().forEach(name => { inputs[name].check() }); } render() { return ( <div> <Input addInput={(c) => this.addInput(c)} name="A"/> <Input addInput={(c) => this.addInput(c)} name="B"/> <Input addInput={(c) => this.addInput(c)} name="C"/> <button onClick={() => this.checkAll()}>click here</button> </div> ); } } ReactDOM.render( <Hello initialName="World"/>, document.getElementById('container') );<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js"></script> <div id="container"> <!-- This element's contents will be replaced with your component. --> </div>
【问题讨论】:
-
您必须包含相关代码部分才能重现该问题。
-
您好,我只是想了解一下react组件的渲染顺序。
-
@YuryTarabanko 代码 sn-p 添加请检查
标签: reactjs virtual-dom