在父组件中发生事件之后更新子组件中的道具?

时间:2019-10-23 17:25:29

标签: reactjs

采用2个组成部分:

ParentComponent ChildComponent

ParentComponent在渲染器中设置ChildComponent:

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

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

我想我的困惑是,我知道如何设置初始变量x,但后来不知道如何更改。

3 个答案:

答案 0 :(得分:1)

将您的状态提升到Parent,然后将其通过Child传递到props

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>
    }
}

答案 1 :(得分:1)

您可以在Parent状态下进行管理,然后将状态值作为道具传递给Child

子组件。

const ChildComponent = props => {
   return <div>{props.x}</div>;
};

父组件

class Parent extends Component {
  constructor(props) {
    super(props);
    this.state = {
       x: "default value"
    };
}

changeX = x => {
   this.setState({
      x: x
   });
};

render() {
  return (
    <div>
     <ChildComponent x={this.state.x} />
     <button
        onClick={() => {
          this.changeX("x");
       }}
     >
       Change X
     </button>
    </div>
   );
 }
}

这里是codepen

答案 2 :(得分:0)

我将在此处编写父组件的示例,希望它可以解决您的问题:


const y = 'hello';

const handleClick = () => {
   y= 'there'
}

render() {
   return(
      <div>
        < Child x={y} />
        <button onClick={handleClick} />
      </div>
   ) 
}

在第一次加载时,子组件{x}持有“ hello”, 单击后,将举行“那里” << / p>