React兄弟组件间传值,动态更新标题

要实现的就说入上图的效果,在输入框中输入信息,直接更新到另一个组件的标题上

因为没有引进Redux,所以这里要用state和props配合传值,主要的想法就是通过输入框组件的onchange函数监听输入框的值的变化,然后去更新当前页面的state,将state的值传入到另一个组件中,实现兄弟间传值。

父页面引入组件和输入框:

export default class Page23 extends Component {
  static displayName = 'Page23';

  constructor(props) {
    super(props);
    console.log(props);
    this.state = {
      name:'111',
    };
    
  }
  onChange = (value) => {
    this.setState({name:value});
  };
  render() {
    const name1 = this.state.name
    return (
      <div className="page23-page"><br/><br/>
        <TestimonialCard name={name1} />
         <Input
            hasClear
            defaultValue="clear by click"
            size="small"
            aria-label="input with config of hasClear" value={this.state.name} onChange={this.onChange} />
      </div>
    );
  }
}

下面是组件TestimonialCard关于传值的代码:

constructor(props) {
    super(props); 
      this.state = {name:props.name};
   
  }

  componentWillReceiveProps(props){
      this.state = {name:props.name};

  }

通过继承得到初始值,通过函数更新变化的值。

猜你喜欢

转载自blog.csdn.net/u013455430/article/details/86248027