在用React+Redux+Immutable遇到的一个问题:
某些组件是通过 动态ReactDOM.render方式加入到页面(例如按钮点击时才渲染到页面),这样创建的组件在父级state改变时,动态创建的子组件props并不会改变
- 是ReactDOM.render 做了一层拷贝?
- 如果既想做到动态ReactDOM.render,又想子组件响应父级state改变,要如何处理
我抽象简化了代码,在线运行: http://codepen.io/anon/pen/OMxppZ
代码如下:
'use strict';
import React from 'react'
import ReactDOM from 'react-dom'
class A extends React.Component {
constructor(props) {
super(props);
this.state = {
name: 'tom'
}
}
dynamic() {
ReactDOM.render(<B name={this.state.name} changeName={this.changeName.bind(this)} type={false}/>, document.getElementById('box'))
}
changeName() {
this.setState({
name: 'tom->' + Date.now()
});
}
render() {
return <div>
顶层显示的姓名: {this.state.name}
<B name={this.state.name} changeName={this.changeName.bind(this)} type={true}/>
<div id="box"></div>
<button onClick={this.dynamic.bind(this)}>动态添加模块</button>
</div>
}
}
class B extends React.Component {
render() {
return <div>
{this.props.type ? '(A)直接作为子组件方式' : '(B)动态ReactDOM.render方式'}
- 姓名:【{this.props.name}】
<button onClick={this.props.changeName}>修改姓名</button>
</div>
}
}
ReactDOM.render(
<A/>,
document.getElementById('example')
);