使用方法的React函数式组件

10

如果我们想要创建一个功能性无状态组件,但是希望其方法能够访问道props,我们该如何做?在这种情况下是否存在通用规则或最佳实践?

例如:

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

根据我的经验,内部props总是与给定的props不同。

如果我不需要状态(使用Redux),但仍希望使用访问props的方法,是否仍然应该使用类而不是无状态函数?


1
为什么只调用没有参数的doSomething()函数?看起来你需要将doSomething()改为doSomething(props)才有意义。 - koo
1
doSomething(/*props you are passing is undefined*/) - Yury Tarabanko
3个回答

4
在函数组件中使用函数是完全可以的。事实上,最近在React 16.8中引入的React hooks,就是为了通过特殊钩子将状态和生命周期事件带给函数组件,使函数组件更加方便。
但是,正如其他人所提到的,您需要向函数传递正确的参数:doSomething(props) 或者根本不传递参数,相应地在函数声明本身中也不要指望它们:function doSomething()

3

doSomething()记录undefined,因为调用doSomething(missing props)时未传递内部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。

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
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接