如何在React子功能中访问道具

时间:2019-07-28 22:05:59

标签: reactjs

我试图从一个教程中学习一些关于React的知识,但是从子类访问App.js中创建的数据有些麻烦。这是App.js:

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

function App() {

  const [state, setState] = useState
  (
    {
      todos: [
        {
        id: 1,
        title: 'Take out the trash',
        completed: false
        },
        {
        id: 2,
        title: 'Dinner with wife',
        completed: false
        },
        {
        id: 3,
        title: 'Meeting with boss',
        completed: false
        },
        ]

    }

    );

  console.log(state.todos)
  return (
    <div className="App">
    <Todos todos={state.todos}/>
    </div>
  );
}

export default App;

这是孩子班:

 import React from 'react';
 function Todos() {
      //console.log(props.todos)
      return (
        <div>
        <h1>Todos</h1>
        </div>
      );
    }

    export default Todos;

当我尝试将todos数组写入控制台时,它会显示消息:

./src/components/Todos.js
  Line 4:  'props' is not defined  no-undef

一个人将如何访问这些属性?看起来它们是根据React Chrome附加组件在“道具”下定义的。

1 个答案:

答案 0 :(得分:2)

Child组件接收props作为参数。

 import React from 'react';

 function Todos(props) {
      console.log(props.todos)
      return (
        <div>
        <h1>Todos</h1>
        </div>
      );
    }

 export default Todos;

使用ES6,您还可以在参数中对这些props进行解构。

 import React from 'react';

 function Todos({ todos }) {
      console.log(todos)
      return (
        <div>
        <h1>Todos</h1>
        </div>
      );
    }

 export default Todos;

请参阅沙箱:https://codesandbox.io/s/affectionate-wilbur-15nd2