【问题标题】:Do functional components have props in react?功能组件在反应中有道具吗?
【发布时间】:2020-10-13 22:13:10
【问题描述】:

我们能否在 react 的功能组件中使用 props,如果可以,如何使用。 我正在尝试做

console.log(this.props) 

在功能组件中的返回函数上方,但它一直给我错误。

【问题讨论】:

标签: reactjs react-props react-component react-functional-component react-class-based-component


【解决方案1】:

是的。您可以像这样直接(使用props)在功能组件中传递道具:

function myFunc(props){
  console.log(props.content);
  return <div>{props.content}</div>;
}

假设传入的props有元素content

澄清一下,函数组件中没有this,因为它们根本不是类!相反,您将props 直接传递到函数中。

事实上,它可能是你在 React 中学习的第一件事。所以如果你是新手,那么我建议the tutorial here

【讨论】:

    【解决方案2】:

    是的,像这样,

    props 作为第一个参数传递给函数组件

    export default function Welcome(props) {
      return <h1>Hello, {props.name}</h1>;
    }
    

    在这里阅读这篇文章,它解释了一切:https://medium.com/@PhilipAndrews/react-how-to-access-props-in-a-functional-component-6bd4200b9e0b

    【讨论】:

      【解决方案3】:

      您可以在类组件中访问“this”关键字...尝试如下实现

      import React from 'react'
      
      const Printing=(props)=> {
          console.log(props)
          return (
              <div>
                  
              </div>
          )
      }
      export default Printing
      

      【讨论】:

        猜你喜欢
        • 2019-08-13
        • 1970-01-01
        • 2019-11-01
        • 1970-01-01
        • 2021-04-20
        • 2019-01-14
        • 2021-10-16
        • 1970-01-01
        • 2021-05-31
        相关资源
        最近更新 更多