小编典典

反应:将道具传递给功能组件

reactjs

关于道具和功能组件,我似乎有一个琐碎的问题。基本上,我有一个容器组件,该组件在用户单击按钮时触发的状态更改后呈现一个Modal组件。模态是一个无状态的功能组件,其中包含一些输入字段,这些输入字段需要连接到容器组件内部的功能。

我的问题:当用户与无状态Modal组件内的表单字段进行交互时,如何使用父组件内的功能来更改状态?我是否错误地传递了道具?提前致谢。

容器

export default class LookupForm extends Component {
    constructor(props) {
        super(props);

        this.state = {
            showModal: false
        };
    }
    render() {
        let close = () => this.setState({ showModal: false });

        return (
            ... // other JSX syntax
            <CreateProfile fields={this.props} show={this.state.showModal} onHide={close} />
        );
    }

    firstNameChange(e) {
      Actions.firstNameChange(e.target.value);
    }
};

功能(模态)组件

const CreateProfile = ({ fields }) => {
  console.log(fields);
  return (
      ... // other JSX syntax

      <Modal.Body>
        <Panel>
          <div className="entry-form">
            <FormGroup>
              <ControlLabel>First Name</ControlLabel>
              <FormControl type="text"
                onChange={fields.firstNameChange} placeholder="Jane"
                />
            </FormGroup>
  );
};

示例:说我想this.firstNameChange从Modal组件中调用。我猜想将道具传递给功能组件的“破坏性”语法让我有些困惑。即:

const SomeComponent = ({ someProps }) = > { // ... };


阅读 223

收藏
2020-07-22

共1个答案

小编典典

您需要为要调用的每个函数分别传递每个prop

<CreateProfile
  onFirstNameChange={this.firstNameChange} 
  onHide={close}
  show={this.state.showModal}
/>

然后可以在CreateProfile组件中执行

const CreateProfile = ({onFirstNameChange, onHide, show }) => {...}

进行解构后,会将匹配的属性名称/值分配给传入的变量。名称只需要与属性匹配

或者只是做

const CreateProfile = (props) => {...}

并在每个地方拨打电话props.onHide或尝试访问的任何道具。

2020-07-22