简体   繁体   English

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

[英]React: Passing props to function components

I have a seemingly trivial question about props and function components.我有一个关于道具和功能组件的看似微不足道的问题。 Basically, I have a container component which renders a Modal component upon state change which is triggered by user click on a button.基本上,我有一个容器组件,它在用户单击按钮触发的状态更改时呈现模态组件。 The modal is a stateless function component that houses some input fields which need to connect to functions living inside the container component. modal 是一个无状态的函数组件,它包含一些需要连接到容器组件内的函数的输入字段。

My question: How can I use the functions living inside the parent component to change state while the user is interacting with form fields inside the stateless Modal component?我的问题:当用户与无状态模态组件内的表单字段交互时,如何使用父组件内的函数来更改状态? Am I passing down props incorrectly?我是否错误地传递了道具? Thanks in advance.提前致谢。

Container容器

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

Function (Modal) Component功能(模态)组件

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

Example: say I want to call this.firstNameChange from within the Modal component.示例:假设我想从 Modal 组件中调用this.firstNameChange I guess the "destructuring" syntax of passing props to a function component has got me a bit confused.我猜想将 props 传递给函数组件的“解构”语法让我有点困惑。 ie: IE:

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

You would need to pass down each prop individually for each function that you needed to call您需要为需要调用的每个函数单独传递每个道具

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

and then in the CreateProfile component you can either do然后在 CreateProfile 组件中你可以做

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

with destructuring it will assign the matching property names/values to the passed in variables.通过解构,它将匹配的属性名称/值分配给传入的变量。 The names just have to match with the properties名称只需要与属性匹配

or just do或者只是做

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

and in each place call props.onHide or whatever prop you are trying to access.并在每个地方调用props.onHide或您尝试访问的任何道具。

I'm using react function component我正在使用反应功能组件
In parent component first pass the props like below shown在父组件中首先传递如下所示的道具

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;

Then use the props in child component like below shown然后使用子组件中的道具,如下所示

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

An addition to the above answer.对上述答案的补充。

If React complains about any of your passed props being undefined , then you will need to destructure those props with default values (common if passing functions, arrays or object literals) eg如果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
}) => {...}

just do this on source component只需在源组件上执行此操作

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

then do this on destination component然后在目标组件上执行此操作

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

A variation of finalfreq's answer finalfreq 答案的变体

You can pass some props individually and all parent props if you really want (not recommended, but sometimes convenient)如果你真的想要,你可以单独传递一些道具和所有父道具(不推荐,但有时很方便)

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

and then in the CreateProfile component you can just do然后在 CreateProfile 组件中你可以做

const CreateProfile = (props) => { 

and destruct props individually并单独销毁道具

const {onFirstNameChange, onHide, show }=props;

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

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