【发布时间】: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 应该看起来像<FontChooser min='4' max='40' size='16' text='Fun with React!' bold={false}/>因为 'false' 是一个非空字符串,所以它是真实的。 -
这能回答你的问题吗? How are boolean props used in React?
标签: javascript reactjs boolean jsx conditional-operator