在Pract中将道具传递给子组件作为状态

时间:2016-12-14 20:34:57

标签: reactjs state parent

我有一个包含此Modal组件的列表。如果用户单击列表中的某一行,则该行中的道具将向下传递到Modal Component

当道具传递给Modal时,我想调用componentWillReceiveProps来设置作为Modal状态的一部分传递的道具。我之所以这样做,是因为titlestatuscost之类的道格最终将成为通过模态状态更新的受控输入。

我唯一的问题是componentWillReceiveProps只被调用一次而且道具不会传递到Modal的状态。有没有办法将这些道具作为状态传递给子组件?

我正在使用React-Bootstrap

中的模态

父组件:

        <AdditionalPaymentsModal 
          status={'New'}
          id= {null} 
          title={'testong'}
          cost={''} />

子组件:

class AdditionalPaymentsModal extends Component {
  constructor(props){
    super(props);
    this.state = {
      showModal: this.props.showModal,
    };
    this.close = this.close.bind(this);
    this.open = this.open.bind(this);
  }

  close() {
    this.setState({ showModal: false });
  }

  open() {
    this.setState({ showModal: true });
  }

  componentWillReceiveProps(nextProps){  
    console.log("SETTING THE STATE", this.state);
      this.setState({
        id: nextProps.id,
        title:nextProps.title, 
        status: nextProps.status, 
        cost:nextProps.date
    })
  }

render(){
  const {id, title, status, cost} = this.props;

  return (
    <div>​
        <Button
          onClick={this.open}>
          Open
        </Button>
        <Modal show={this.state.showModal} onHide={this.close}>
          <Modal.Header closeButton>
            <Modal.Title>New Edit Cost</Modal.Title>
          </Modal.Header>
          <Modal.Body>
          {this.state.title}
          {this.state.id}
          {this.state.cost}
          {this.state.status}
          </Modal.Body>
          <Modal.Footer>
            <Button onClick={this.close}>Cancel</Button>
          </Modal.Footer>
        </Modal>
      </div>
   );
  }
}

1 个答案:

答案 0 :(得分:2)

看起来你并没有修改传入的props;如果您只想展示它们,那么他们就不需要进入state

您已在render函数中初始化道具:

const {id, title, status, cost} = this.props;

您需要做的就是引用它们 - 您的构造函数无需将它们放在state中:

render () { ... <Modal.Body> {title} {id} {cost} {status} </Modal.Body> ... }