jsx的属性绑定

jsx的state可绑定到html的属性上

html的属性后面使用{}符号来绑定react组件中的值

<script type="text/babel">
    class App extends React.Component {
    
    
      constructor(){
    
    
          super()
          this.state = {
    
    
            title:'这个是标题'
          }
        }
      render(){
    
    
        return(
          <div>
            <h2 title={
    
    this.state.title}>这个是标题</h2>
          </div>
        )
      }
    }
    ReactDOM.render(<App/>,document.getElementById("app"))
  </script>

jsx的state可绑定到html的class中

  • 因为再react中,已经使用了class 作为创建组件的语法糖,因此和html 中的class重名了,react不推荐使用’class’这个单词来作为类的名称,因此我们使用className
<h2 className="title box "></h2>
  • 那么如何在className中动态绑定class呢?
    可以使用{}符号包裹class的名称,然后再用js的写法来动态绑定class
//active为true or false? 如果为true则添加'active' ,false添加 '',即不添加class名称
 <h2 className={
    
    'title box' + ( this.state.active ? "active" : '')}></h2>

jsx的state可绑定到html的style

html的style属性,即内联样式,jsx可以绑定

  • style同样使用{}符号来进行绑定
  • {}符号中添加{},代表一个对象,对象中必须严格按照js的对象格式书写,如果键值不添加"",那么视为变量名称
  • 对象中的css名称使用驼峰命名法
<h2 style={
    
    {
    
    color:'red',fontSize:this.state.fontSize}}>style</h2>

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/MS6324_ZAKU/article/details/113967081
JSX