【问题标题】:React functional components with methods用方法反应功能组件
【发布时间】:2019-07-24 03:37:57
【问题描述】:

如果我们想要制作一个功能性的无状态组件,但我们想要能够访问 props 的方法,我们该怎么做?当涉及到这样的事情时,是否有一般规则或最佳实践

例如

function Stateless(props) {
   function doSomething(props) {
      console.log(props);
   }
  doSomething() // logs 'undefined'
return (
  <div> some stuff </div>
}

至少在我的经验中,里面的道具总是不是给定的道具。

如果我不需要状态(使用 Redux)但仍然想要访问 props 的方法,那么使用类而不是无状态函数仍然是一种好习惯吗?

【问题讨论】:

  • 为什么只调用不带参数的doSomething()?看来您必须将 doSomething() 更改为 doSomething(props) 才有意义
  • doSomething(/*props you are passing is undefined*/)

标签: javascript reactjs


【解决方案1】:

在函数式组件中使用函数是非常好的。事实上,最近在 React 16.8 中引入的 React hooks 都是为了通过 special hooks 为功能组件带来状态和生命周期事件,从而使功能组件更加方便。

但正如其他人所提到的,您需要将正确的参数传递给您的函数:doSomething(props) 或者根本不传递参数,因此永远不要在函数声明本身中期望它们:function doSomething()

【讨论】:

    【解决方案2】:
    function Stateless(props) {
       function doSomething() { // 1. props is accessible inside the function so you can skip the parameter
          console.log(props);
       }
      doSomething();
    return (
      <div> some stuff </div>
    )//2. missing paranthesis
    }
    

    【讨论】:

      【解决方案3】:

      doSomething() 记录未定义,因为当您调用 doSomething(missing props) 时未传递内部 props 变量。 您可以删除内部道具:

      function Stateless(props) {
        function doSomething() {
          console.log(props);
        }
        doSomething();
        return (
          <div> some stuff </div>
        );
      }
      

      或者在你的组件之外声明 doSomething:

      function doSomething(props) {
        console.log(props);
      }
      function Stateless(props) {
        doSomething(props);
        return (
          <div> some stuff </div>
        );
      }
      

      两者都可以。第一个可能更容易,但如果您的组件经常重绘,那么第二个性能更高,因为您只声明了一次 doSomething。

      【讨论】:

        猜你喜欢
        • 2020-10-29
        • 1970-01-01
        • 2019-08-29
        • 2023-02-21
        • 1970-01-01
        • 2021-04-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多