是否可以在反应渲染函数中返回空? [英] Is it possible to return empty in react render function?

查看:35
本文介绍了是否可以在反应渲染函数中返回空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通知组件,我有一个超时设置.超时后我调用 this.setState({isTimeout:true}).

我想做的是如果已经超时,我只想渲染什么:

render() {让 finalClasses = "";+ (this.state.classes || "");如果(是超时){返回 ();//这里有一些语法错误}返回(<div>{this.props.children}</div>);}

问题是:

<块引用>

返回();//这里有一些语法错误

解决方案

是的,你可以,但如果你不想rendernull而不是空白> 组件中的任何内容,如下所示:

return (null);

<小时>

另一个重要的一点是,在 JSX 中,如果你有条件地渲染元素,那么在 condition=false 的情况下,你可以返回这些值中的任何一个 false, null, undefined, true.根据 DOC:

<块引用>

booleans (true/false)、null 和 undefined有效子项,它们将被忽略意味着它们根本不呈现.

所有这些 JSX 表达式都将渲染为相同的东西:

<div></div><div>{false}</div><div>{null}</div><div>{未定义}</div><div>{true}</div>

示例:

只有奇数值会被渲染,因为对于偶数值我们返回null.

const App = ({ number }) =>{如果(数量%2){返回 (<div>号码:{号码}

)}返回(空);//===>注意这里,对于偶数值返回 null}常量数据 = [1,2,3,4,5,6];ReactDOM.render(<div>{data.map(el => <App key={el} number={el}/>)}

,document.getElementById('app'))

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script><div id='app'/>

I have a notification component, and I have a timeout setting for it. After timeout I call this.setState({isTimeout:true}).

What I want to do is if already timeout, I want just render nothing:

render() {
  let finalClasses = "" + (this.state.classes || "");
  if (isTimeout){
    return (); // here has some syntax error
  }
  return (<div>{this.props.children}</div>);
}

The problem is:

return (); // here has some syntax error

解决方案

Yes you can, but instead of blank, simply return null if you don't want to render anything from component, like this:

return (null);


Another important point is, inside JSX if you are rendering element conditionally, then in case of condition=false, you can return any of these values false, null, undefined, true. As per DOC:

booleans (true/false), null, and undefined are valid children, they will be Ignored means they simply don’t render.

All these JSX expressions will render to the same thing:

<div />

<div></div>

<div>{false}</div>

<div>{null}</div>

<div>{undefined}</div>

<div>{true}</div>

Example:

Only odd values will get rendered, because for even values we are returning null.

const App = ({ number }) => {
  if(number%2) {
    return (
      <div>
        Number: {number}
      </div>
    )
  }
  
  return (null);           //===> notice here, returning null for even values
}

const data = [1,2,3,4,5,6];

ReactDOM.render(
  <div>
    {data.map(el => <App key={el} number={el} />)}
  </div>,
  document.getElementById('app')
)

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='app' />

这篇关于是否可以在反应渲染函数中返回空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆