首页 > 解决方案 > 在父组件中的事件之后更新子组件中的道具?

问题描述

取2个组件:

父组件子组件

ParentComponent 在 render 中设置 ChildComponent:

render() {
    return (
        <ChildComponent x='default value' />
    )
}

然后,ParentComponent 想要将 x='default value' 更改为 'hello',可能是为了响应 onClick 事件。

我认为我的困惑是,我知道如何设置初始变量 x,但不知道以后如何更改它。

标签: reactjs

解决方案


将您的状态提升到您的状态Parent并将其传递给Childviaprops

const Parent = () =>{
    const [title, setTitle] = useState('foo')

    return(
        <>
            <Child title={title} />
            <button onClick={() => setTitle('bar')}>Change to bar</button>
        </>
    )
}

const Child = ({ title }) => <div>{title}</div>

对于class基于组件

class Parent extends React.Component {
    state = { title: 'foo' }

    render() {
        const { title } = this.state
        return (
            <>
                <button onClick={() => this.setState({ title: 'bar' })}>Change to bar</button>
                <Child title={title} />
            </>
        )
    }
}

class Child extends React.Component {
    render() {
        const { title } = this.props
        return <div>{title}</div>
    }
}

推荐阅读