我正在尋找幫助將頁面呈現前從屬性字符串轉換爲布爾值。粗體屬性將被設置爲「真」或「假」的字符串。我已經設置了屬性的狀態,但字符串'false'仍然是true。我目前正試圖在我的handleClick函數中轉換爲布爾值,但如果在頁面呈現前我需要進行轉換。如果「bold」屬性設置爲「true」,則應以粗體顯示文本
HTML
<script type="text/jsx">
ReactDOM.render(
<div>
<FontChooser min='4' max='40' size='16' text='Fun with React!' bold='true'/>
</div>, document.getElementById('container'));
</script>
JS
class FontChooser extends React.Component {
constructor(props) {
super(props);
this.state = {hidden: 'true', size: this.props.size, bold: this.props.bold, min : this.props.min, max: this.props.max, color: 'black'};
}
handleClick() {
if(this.state.hidden == 'true') {
if(this.props.bold == "true") {
this.setState({bold: true})
} else {
this.setState({bold: false})
}
this.setState({hidden: ''});
}
else {
this.setState({hidden: 'true'});
}
}
decrease() {
if (this.state.size >= Number(this.state.min) +1)
this.setState({size: Number(this.state.size) -1});
if(this.state.size == Number(this.state.min) +1|| this.state.size == Number(this.state.min)) {
this.setState({color: 'red'})
} else {
this.setState({color: 'black'})
}
}
increase() {
if (this.state.size <= Number(this.state.max) -1)
this.setState({size: Number(this.state.size) +1});
if(this.state.size == Number(this.state.max) -1|| this.state.size == Number(this.state.max)) {
this.setState({color: 'red'})
} else {
this.setState({color: 'black'})
}
}
toggle() {
this.setState({bold: !this.state.bold});
}
render() {
var weight = this.state.bold ? 'bold' : 'normal';
var checked = this.state.bold ? 'true' : '';
var inlineStyle = {
fontSize: this.state.size,
fontWeight: weight,
};
var fontSizeSpanStyle = {
color: this.state.color
}
return(
<div>
<input type="checkbox" id="boldCheckbox" checked={checked} hidden={this.state.hidden}onClick={this.toggle.bind(this)} />
<button id="decreaseButton" hidden={this.state.hidden} onClick={this.decrease.bind(this)} >-</button>
<span id="fontSizeSpan" hidden={this.state.hidden} style={fontSizeSpanStyle} >{this.state.size}</span>
<button id="increaseButton" hidden={this.state.hidden} onClick={this.increase.bind(this)} >+</button>
<span id="textSpan" onClick={this.handleClick.bind(this)} style={inlineStyle} >{this.props.text}
</span>
</div>
);
}
}
是否有任何理由不使用布爾值? –
這是一項家庭作業,並有一個自動平地機,其值已經設置爲字符串。 –
如果道具是字符串,請將它們保存爲布爾值。目前,您在狀態中使用了布爾值和字符串,例如'bold:this.props.bold'使用一個字符串,'this.setState({bold:true})'使用一個布爾值。這意味着你將不能使用普通的'!this.state.bold',但你將不得不使用'this.state =='false''。 – Sulthan