传递给组件状态时,`this.props` 是否总是 return 真值?
Does `this.props` always return a truthy value when passed to component state?
我想将 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
应该 return false 但三元运算符执行 'bold' 只有在 this.props.bold
为真时才应该执行。它似乎将 this.props.bold
视为真值而不是假值,即使它在组件 属性.
中设置为假
那么当我们将它传递给组件状态时,this.props
总是 return 一个真值吗?即使在组件 prop 定义中设置为 'false'?
您将 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}/>
我想将 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
应该 return false 但三元运算符执行 'bold' 只有在 this.props.bold
为真时才应该执行。它似乎将 this.props.bold
视为真值而不是假值,即使它在组件 属性.
那么当我们将它传递给组件状态时,this.props
总是 return 一个真值吗?即使在组件 prop 定义中设置为 'false'?
您将 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}/>