父组件:
class PageCheckbox extends React.Component {
constructor (props) {
super(props)
this.state = {
checkboxCheck: true
}
}
test () {
this.state.checkboxCheck = false
console.log(this.state.checkboxCheck)
}
render () {
return <section className="checkbox-wrapper">
<Checkbox checked={ this.state.checkboxCheck }>checkbox</Checkbox>
<Button clickHandler={ this.test.bind(this) }>test</Button>
</section>
}
}
子组件
class Checkbox extends Component {
constructor (props) {
super(props)
this.state = {
checked: props.checked
}
}
componentWillReceiveProps (nextProps) {
console.log('received', nextProps)
this.setState({
checked: nextProps.checked
})
}
render () {
return <label className={ `${ this.getLibName() }-checkbox` }>
<span className={ `${ this.getLibName() }-checkbox__input` }>
<span className={ this.formatClsNames(
`${ this.getLibName() }-checkbox__selector`,
this.state.checked ? `${ this.getLibName() }-checked` : '',
this.props.disabled ? `${ this.getLibName() }-disabled` : ''
) }></span>
<input type="checkbox"
checked={ this.state.checked }
className={ `${ this.getLibName() }-origin-el` }
onChange={ this.onChange.bind(this) }/>
</span>
<span className={ `${ this.getLibName() }-checkbox__label` }>
{ this.props.children }
</span>
</label>
}
}
Checkbox.propTypes = {
checked: PropTypes.bool
}
Checkbox.defaultProps = {
checked: false
}
在父组件中点了按钮之后,并没有调用子组件中的componentWillReceiveProps
,想请问下是为什么?找了半天的资料没找到原因。。
React改变组件状态要通过调用setState的方式,不能直接改变state的值,你父组件中test方法应该改为: