【问题标题】:Does `this.props` always return a truthy value when passed to component state?当传递给组件状态时,`this.props` 是否总是返回一个真实值?
【发布时间】:2020-10-11 19:04:45
【问题描述】:

我想将 props 传递给我的 react 组件,并有一个函数可以在粗体和正常之间切换跨度的字体粗细。

我的 React 组件:

ReactDOM.render(
  <div>
    <FontChooser min='4' max='40' size='16' text='Fun with React!' bold='false'/>
   </div>,
document.getElementById('container'))
;

我正在尝试将 bold = 'false' 属性传递给组件的初始状态,如下所示:

class FontChooser extends React.Component {

    constructor(props) {
    super(props);
    this.state = {
        hidden: true,
        bold: this.props.bold,
        size: 16 
    }
    }

然后我就有了函数

toggleBold() {
        this.setState ({
            bold: !this.state.bold
        });
    }

它应该呈现:

render() {
        var weight = this.state.bold ? 'bold':'normal';

    return(
           <div>
           <input type="checkbox" id="boldCheckbox" onChange={this.toggleBold.bind(this)}
           <span id="textSpan" style ={{fontWeight: weight, fontSize: this.state.size }}>. 
                 {this.props.text}</span>
           </div>

我的问题是 this.props.bold 应该返回 false 但三元运算符执行“粗体”,只有在 this.props.bold 为 true 时才应该执行。似乎它将this.props.bold 视为一个真值而不是假值,即使它在组件属性中设置为假。

那么当我们将this.props 传递给组件状态时,它是否总是返回一个真值?即使在组件道具定义中设置为'false'?

【问题讨论】:

  • 您将 false 作为字符串而不是实际的 false 值传递,您的 JSX 应该看起来像 &lt;FontChooser min='4' max='40' size='16' text='Fun with React!' bold={false}/&gt; 因为 'false' 是一个非空字符串,所以它是真实的。
  • 这能回答你的问题吗? How are boolean props used in React?

标签: javascript reactjs boolean jsx conditional-operator


【解决方案1】:

您将 bold 属性作为字符串传递,并且由于传递的值不是空字符串,因此 this.state.bold 在三元中被评估为 true

<FontChooser min='4' max='40' size='16' text='Fun with React!' bold='false'/>
                                                                    ^

let bold = 'false'

console.log(!!bold)

解决方案,将 bold 的值传递为布尔值。

<FontChooser min='4' max='40' size='16' text='Fun with React!' bold={false}/>

【讨论】:

    猜你喜欢
    • 2019-01-06
    • 2021-11-22
    • 1970-01-01
    • 2019-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-03
    • 1970-01-01
    相关资源
    最近更新 更多