通过在React.js中传递值使字体粗体变粗

aaa*_*umi 3 reactjs

我想通过单击复选框输入将字体粗细从正常更改为粗体.

我试图应用三元运算符,但它不起作用.

bold={ this.state.checkboxState ? this.props.bold : !this.props.bold }
Run Code Online (Sandbox Code Playgroud)

实现此功能的最佳方法是什么?

这是一个codepen演示.

代码

class FontChooser extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            hidden: true,
            checkboxState : true
        }
    }
    toggle(e) {
        this.setState({
            checkboxState : !this.state.checkboxState
        })
        console.log(!this.state.isChecked)
    }

    render() {
        return(
            <div>
                <input type="checkbox" 
                    id="boldCheckbox"
                    checked={this.state.isChecked}
                    onClick={this.toggle.bind(this)}
                />
               <span 
                   id="textSpan" 
                   bold={ this.state.checkboxState ? this.props.bold : !this.props.bold }
               >
                   {this.props.text}
               </span>
           </div>
       );
    }
}

React.render(
    <div>
        <FontChooser text='Fun with React!' bold='false' />
    </div>,
    document.getElementById('container')
);
Run Code Online (Sandbox Code Playgroud)

谢谢你的好意见.

wlh*_*wlh 7

更改<span id="textSpan">为以下内容:

<span 
    id="textSpan" 
    style={ this.state.checkboxState ? { fontWeight: 'normal' } : { fontWeight: 'bold' } }
>
    { this.props.text }
</span>
Run Code Online (Sandbox Code Playgroud)

  • 好答案!稍微整洁一些: `style={{ fontWeight: this.state.checkboxState ? '正常':'粗体' }}` (2认同)