javascript - react : Passing props to function components

标签 javascript reactjs components

我有一个关于 props 和函数组件的看似微不足道的问题。基本上,我有一个容器组件,它在用户单击按钮触发的状态更改时呈现模态组件。模态是一个无状态函数组件,其中包含一些需要连接到容器组件中的函数的输入字段。

我的问题:当用户与无状态 Modal 组件内的表单字段交互时,如何使用父组件内的函数来更改状态?我是否错误地传递了 Prop ?

容器

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>
  );
};

示例:假设我想从 Modal 组件中调用 this.firstNameChange。我想将 props 传递给函数组件的“解构”语法让我有点困惑。即:

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

最佳答案

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

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

然后在 CreateProfile 组件中,您可以执行以下操作

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

通过解构,它将匹配的属性名称/值分配给传入的变量。名称只需要与属性匹配

或者只是做

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

并在每个地方调用 props.onHide 或您尝试访问的任何 prop。

关于javascript - react : Passing props to function components,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39963565/

相关文章:

javascript - 如何为两个 ddp 连接的应用程序使用相同的数据库

javascript - Sequelize,用空白值验证字段的长度

c# - 如果可能的话,是否应该在软件组件内部避免使用线程?

javascript - 如何引用父对象的变量?

javascript - 谷歌地图上突然报错 : TypeError: _. x is not a function

reactjs - Mobx-state-tree 在树内使用 mobx react - 好的还是坏的做法?

javascript - MDC-web 未按预期工作

javascript - 我可以在 React Native 上向 this.props.children 添加额外的回调吗?

javascript - 组件无法解析 $scope 的注入(inject)( Angular 1.3.16)

javascript - 选择组件Vue JS - 默认选择值