我的父组件
中有这个构造函数 constructor (props) {
super(props)
this.state = {
owner,
name: '',
projectToAdd: this.props.defaultProject,
}
}
属性projectToAdd
设置为props传递的值,我需要使用位于我的子组件中的以下函数更改状态的此属性:
handleProjectSelection = (project) => () => {
this.setState({
projectToAdd: project.get('id')
})
}
当我单击子组件中<li>
标记的元素时,将调用此函数:
renderDropdown () {
const { projects } = this.props
const projectsList = projects.map((project) => (
<li className='u-cursor--pointer u-padding-tiny u-font-size--12px'
key={project.get('id')}
onClick={this.handleProjectSelection(project)} >
{project.get('name')}
</li>
))
return (
<div>
<ul className='c-folder-dropdown'
name='projectList'
form='start-retro-form'>
{projectsList}
</ul>
</div>
)
}
如何将状态从子组件更改为父组件?
答案 0 :(得分:1)
将更改处理程序函数prop从您的父级传递给子级。
class Parent{
handleChange = () => {
this.setState({
foo: 'bar'
})
}
render(){
return <Child onChange={this.handleChange} {...this.state}/>
}
}