二、React实现一个计数器-jsx语法-动态class-动态style属性

95 阅读1分钟
  1. {}语法
  2. 属性绑定
  3. 动态绑定class属性 <借助第三方库classnames>
const root = ReactDOM.createRoot(document.querySelector('#root'))

class App extends React.Component {
    constructor() {
        super()
        this.state = {
            counter: 0,
            title: '全局属性'
        }
    }
    
    increment() {
        this.setState({
          counter: this.state.counter + 1
        });
      }

      decrement() {
        this.setState({
          counter: this.state.counter - 1
        })
      }
      
    render() {
        const { title } = this.state
        return (
            // 1. 结构中只能有一个根元素
            <div>
                <h2 title={title}>当前计数:{this.state.counter}</h2>
                <div>
                  <button onClick={this.increment.bind(this)}>自增</button>
                </div>
                <div>
                  <button onClick={this.decrement.bind(this)}>自减</button>
                </div>
                
                <h3 className={`wrap btn ${isActive ? "active" : ""}`}>动态绑定class</h3>
                
                <h3 style={{ color: "red" }}>style</h3>
          </div>
        )
    }
}

root.render(<App />)