【问题标题】:React: How to do conditional checks from render() method in functional Components?React:如何从功能组件中的 render() 方法进行条件检查?
【发布时间】:2019-09-23 23:41:09
【问题描述】:

在我的普通 React 类组件中,我在 render() 方法中做了一些检查,然后返回条件 html 渲染。现在,我正在使用一个反应功能组件,它显然没有 render() 方法......我将如何在这里进行条件检查?只是在普通函数中,然后从这些函数中返回 html 代码?

例如类组件:

render() {
let test;
if (this.state.test ===true) {
    test = (
    <p>This is a test</p>
    )
}

return(
    {test}
)
}

在功能组件中? :

        return (            
            <p >
                {checkIcon()} //normal Javascript functions?
            </p>
        )

【问题讨论】:

  • 你试过了吗?有什么错误吗?使用普通的 JS 函数完全没问题。
  • 您需要将test 作为参数传递。其余的几乎保持不变。
  • 文档为您提供了一个带有功能组件的示例https://reactjs.org/docs/conditional-rendering.html
  • {checkIcon() &amp;&amp; &lt;p&gt;This is a test&lt;/p&gt;}

标签: javascript reactjs function


【解决方案1】:

您可以将功能组件视为类组件的渲染方法,您可以在其中执行与渲染中完全相同的操作,只是您将从arguments 而不是this 接收道具,同样您将获得'除非您使用钩子,否则没有状态。因此,您可以将 test 作为道具传递给功能组件

const MyComponent = ({test}) =>{

    let value;
    if (test ===true) {
        test = (
        <p>This is a test</p>
        )
    }

    return(
        {value}
    )

}

【讨论】:

    【解决方案2】:

    正如其他人所说,您可以在渲染函数中做任何事情,就像您可以对类组件做同样的事情。您可以将功能组件视为类的渲染功能...

    顺便说一句,功能组件不应该包含那么多业务逻辑,最好通过 HOC 和功能组合来增强它们。

    您可能想看看recompose,我的示例从中获得灵感。 (更改test属性并按运行代码sn-p)

    // First create a Generic HOC that embedds the branching logic for you.
    const branch = (predicate, LeftComponent) => RightComponent => props => (
      predicate(props) ? <LeftComponent {...props} /> : <RightComponent {...props} />
    );
    
    // Leave your view component the only job of displaying data to the screen. Avoid any control flow.
    const Test = () => 'this is a test component';
    const Value = ({ value }) => <div>The Value is {value}</div>;
    
    // Create a final component that branches accordingly with the needed check (if props.test is true)
    const Component = branch(
      props => props.test,
      Test
    )(Value);
    
    
    ReactDOM.render(
      <Component test={true} value="£100" />,
      document.getElementById('container')
    );
    <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
    <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
    
    <div id="container"></div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-06
      • 1970-01-01
      • 2019-11-16
      • 1970-01-01
      • 2020-12-22
      • 1970-01-01
      • 2020-05-04
      • 2021-09-02
      相关资源
      最近更新 更多