父→子
传送子组件的属性是父组件传递的,动态修改父组件的值,子组件也会对应的变化
const Item = React.createClass({
render () {
let style = this.props.actived ? { 'border': '1px solid green' } : {}
return <li style={style}>{this.props.name}</li>
}
})
const Comp = React.createClass({
getInitialState () {
return { 'list': [] }
},
componentWillMount () {
//组件装载前修改传入的data
this.state.list = this.props.data.map(item => {
return { 'name': item, 'actived': false }
})
},
componentDidMount () {
//装载完毕三秒后第二个会加上边框
setTimeout(() => {
this.state.list[1].actived = true
this.forceUpdate()
}, 3000)
},
render () {
return <ul>{this.state.list.map(item => {
console.log(item)
return <Item key={item.name} actived={item.actived} name={item.name} />
})}</ul>
}
})
const List = ['AAA', 'BBB', 'CCC', 'DDD']
ReactDOM.render(<Comp data={List} />, document.getElementById('root'))
子→父
父组件将自身方法作为props传给子组件,可以让其调用。ps:记得绑定this
const Item = React.createClass({
render () {
let style = this.props.actived ? { 'border': '1px solid green' } : {}
//onClick触发的方法为父组件传递的方法
return <li onClick={this.props.click} style={style}>{this.props.name}</li>
}
})
const Comp = React.createClass({
getInitialState () {
return { 'list': [] }
},
componentWillMount () {
this.state.list = this.props.data.map(item => {
return { 'name': item, 'actived': false }
})
},
componentDidMount () {
setTimeout(() => {
this.state.list[1].actived = true
this.forceUpdate()
}, 3000)
},
clickHandler (item) {
alert(item.name)
},
render () {
return <ul>{this.state.list.map(item => {
console.log(item)
//把clickHandler作为props.click传递给Item,此处绑定了this
return <Item key={item.name} click={this.clickHandler.bind(this, item)} actived={item.actived} name={item.name} />
})}</ul>
}
})
const List = ['AAA', 'BBB', 'CCC', 'DDD']
ReactDOM.render(<Comp data={List} />, document.getElementById('root'))