在 React 中将 Props 作为状态传递给子组件

Passing Props to Child Component as State in React

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

当 props 被传递到 Modal 时,我想调用 componentWillReceiveProps 来设置传递的 props 作为 Modal 状态的一部分。我这样做是因为 titlestatuscost 等道具最终将成为受控输入,并通过模态框的状态进行更新。

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

我正在使用来自 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>
   );
  }
}

您似乎没有修改传入的 props;如果您只是想显示它们,那么它们不需要在 state.

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

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

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

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