【问题标题】:How to access a function in a stateless component?如何访问无状态组件中的函数?
【发布时间】:2019-10-15 15:31:48
【问题描述】:

我可以访问无状态组件中的函数吗?我知道如果更改为类组件,则可以访问该功能。然而,据我所知。 Hooks 不能与类组件兼容。请随意评论。谢谢。

# This example is incorrect, for describe the idea only.
const StatelessComponent = () => {

  const StatelessComponentFunction = () => {
    return 1;
  }

}

const thisFun = new TestComponent();

let A = thisFun.StatelessComponentFunction();

2019 年 10 月 16 日更新,找到解决方案。

基于“https://hackernoon.com/javascript-state-encapsulation-without-classes-in-2019-97e06c6a9643”和“https://basarat.gitbooks.io/typescript/docs/javascript/closure.html”这些页面上的信息。我找到了解决办法。

修改

const StatelessComponent = () => {

  return {
    StatelessComponentFunction() {
      return 1;
    }
  }

}

const thisFun = StatelessComponent();

console.log(thisFun.StatelessComponentFunction());

【问题讨论】:

    标签: javascript typescript react-native


    【解决方案1】:

    不,使用无状态组件将 jsx 渲染到 DOM。

    您所展示的并不是真正的反应组件,因为它没有返回 jsx。它只是一个JS函数。

    // This example is incorrect, for describe the idea only.
    const TestComponent = () => {
    
      const StatelessComponentFunction = () => {
        return 1;
      }
    
    }
    
    const thisFun = new TestComponent();
    
    let A = thisFun.StatelessComponentFunction();

    无状态组件应该像 react 组件一样实例化 <TestComponent />

    【讨论】:

      【解决方案2】:

      正如@Joey_Gough 提到的。无论是有状态还是无状态组件,您的组件都应该返回 JSX。

      如果您想在无状态组件中执行方法,那么您应该在父组件Class Component 中创建一个函数,并将该函数作为子组件的prop 传递。像这样的:

      class ParentComponent extends Component {
      
        handleClick = () => {
          // Code here
        }
      
        render() {
      
          return(
                  <StatelessComponent onClicked={handleClick} />
          )
        }
      }
      
      const StatelessComponent = (prop) => {
      
        return(
          <button onClick={prop.onClicked></button> 
        )
      }
      

      【讨论】:

        猜你喜欢
        • 2017-07-11
        • 1970-01-01
        • 2021-05-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-10
        • 1970-01-01
        相关资源
        最近更新 更多