繁体   English   中英

React:将道具传递给功能组件

[英]React: Passing props to function components

我有一个关于道具和功能组件的看似微不足道的问题。 基本上,我有一个容器组件,它在用户单击按钮触发的状态更改时呈现模态组件。 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>
  );
};

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

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

您需要为需要调用的每个函数单独传递每个道具

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

然后在 CreateProfile 组件中你可以做

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

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

或者只是做

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

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

我正在使用反应功能组件
在父组件中首先传递如下所示的道具

import React, { useState } from 'react';
import './App.css';
import Todo from './components/Todo'



function App() {
    const [todos, setTodos] = useState([
        {
          id: 1,
          title: 'This is first list'
        },
        {
          id: 2,
          title: 'This is second list'
        },
        {
          id: 3,
          title: 'This is third list'
        },
    ]);

return (
        <div className="App">
            <h1></h1>
            <Todo todos={todos}/> //This is how i'm passing props in parent component
        </div>
    );
}

export default App;

然后使用子组件中的道具,如下所示

function Todo(props) {
    return (
        <div>
            {props.todos.map(todo => { // using props in child component and looping
                return (
                    <h1>{todo.title}</h1>
                )
            })}
        </div>  
    );
}

对上述答案的补充。

如果React抱怨您传递的任何props undefined ,那么您将需要使用default值解构这些道具(常见于传递函数、数组或对象字面量),例如

const CreateProfile = ({
  // defined as a default function
  onFirstNameChange = f => f,
  onHide,
  // set default as `false` since it's the passed value
  show = false
}) => {...}

只需在源组件上执行此操作

 <MyDocument selectedQuestionData = {this.state.selectedQuestionAnswer} />

然后在目标组件上执行此操作

const MyDocument = (props) => (
  console.log(props.selectedQuestionData)
);

finalfreq 答案的变体

如果你真的想要,你可以单独传递一些道具和所有父道具(不推荐,但有时很方便)

<CreateProfile
  {...this.props}
  show={this.state.showModal}
/>

然后在 CreateProfile 组件中你可以做

const CreateProfile = (props) => { 

并单独销毁道具

const {onFirstNameChange, onHide, show }=props;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM