【问题标题】:Set parent props to child component variable将父道具设置为子组件变量
【发布时间】:2020-02-07 13:05:46
【问题描述】:

我是 React 新手,我想将父 props 分配给子组件的变量 like=>

this.setState({
   tsmodel : props.dataSource
})

这里是父代码 =>

<TimeSheetDialog 
          fromdate={this.state.fromdate}
          todsate={this.state.todate}         
          show={this.state.showmodel}
          onHide={this.handleModelShow}
          dataSource={this.state.selectedtsrow}/>

我将这个selectedtsrow 变量传递给子组件。

这是我的孩子代码=>

export default class TimeSheetDialog extends React.Component{

    constructor(props){
        super(props);

        this.state = {
           tsmodel : props.dataSource
        };    
    }

 render(){
   return(
   .
   .
   .



     <DatePicker
         selected={ this.state.tsmodel.tsdate }
         onChange={(e)=>this.handleDateChange("tsdate",e)}
         dateFormat="dd-MM-yyyy"
         />

)

}
}

我不能那样使用,因为这个 tsmodel 总是 undefined

我的要求是我不想使用this.props.dataSource.tsdate,我想使用this.state.tsmodel.tsdate

如何将此父属性设置为子变量?我错过了逻辑吗?

【问题讨论】:

  • console.log(this.state.tsmodel) => 这会返回什么?
  • 我尝试在构造函数和 componentwillMount 中这样打印,但两者都未定义,但在渲染块内部它有数据。
  • 在构造函数中打印 - props.dataSource。那是未定义的吗?同时分享console.log(this.state.tsmodel)的输出
  • @MonicaAcha,对不起,在构造函数中,我得到了一个空对象。不是未定义的。
  • 可能父母正在发送一个空对象。请确保您在父母中更新您的状态。或者分享设置状态的相关代码供我们调试

标签: reactjs


【解决方案1】:

根据我的经验,最好的方法是将绑定到父级的函数传递给子级,这会更改父级中的必要内容。所以

parent {
    setValue = (value) => {
         this.parentValue = value;
    }

    render() {
         return(<child setParentValue={this.setValue}>);
    }
}

child() {
    someFunction = () => {
        this.props.setParentValue("value");
    }
}

至于改变道具,只有父母(祖父母)的父母才能改变给予父母的道具,所以也许基本上一个功能是最好的?

【讨论】:

  • 一般我也是这样用的,但是现在我想在父子之间尽可能多地拆分代码,我不想把这个值依赖于父函数。
【解决方案2】:

这是因为我的子变量没有刷新。所以我使用了componentWillReceiveProps方法like=>

componentWillReceiveProps(nextProps) {
   this.setState({
      tsmodel : this.props.dataSource
})
}

现在 tsmodel 已更新。

如果您不想使用 componentWillReceiveProps ,请使用 child like=> 中的 key 属性=>

<TimeSheetDialog 
          fromdate={this.state.fromdate}
          todsate={this.state.todate}         
          show={this.state.showmodel}
          onHide={this.handleModelShow}
          dataSource={this.state.selectedtsrow}
          key = {this.state.selectedtsrow.id}/>

如果selectedtsrow 改变了,这个组件将被重新渲染。更多信息在这里=> more info

【讨论】:

    猜你喜欢
    • 2017-02-17
    • 2019-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-22
    相关资源
    最近更新 更多