React(八)—— 获取真实DOM

2019-02-22  本文已影响4人  感觉不错哦
弥补一个知识点,默认props,本来写上篇文章的,忘了
     class HelloWorld extends React.Component{
         constructor(props){
             super(props)
         }
       
        
         render(){
             return(
                <h1>{this.props.name}</h1>
             )
         }
     }
     HelloWorld.defaultProps={
         name:'React'
     }
     ReactDOM.render(<HelloWorld/>,document.getElementById('div'))

当然默认的权重是最低的,实际开发很多时候还是使用三元

 <h1>{this.props.name?this.props.name:'React'}</h1>
获取真实DOM节点

React中的DOM也是虚拟DOM(virtual DOM),这点跟我们以前讲的Vue非常类似。只有当它插入文档以后,才会变成真实的DOM。React也是在虚拟DOM发生变化时,进行比对后,只渲染变化的部分,它是React极高性能的主要原因之一。

<script type="text/babel">
     class HelloWorld extends React.Component{
         constructor(props){
             super(props)
         }
       
        
         render(){
             return(
                <div>
                  <input type="text" />
                  <input type="button" value="Focus the text input"/>
                </div>
             )
         }
     }
     ReactDOM.render(<HelloWorld/>,document.getElementById('div'))
</script>

OK 初始化一下,写个效果是什么呢?就是点击Button的时候,给input添加光标

<script type="text/babel">
     class HelloWorld extends React.Component{
         constructor(props){
             super(props)
         }
         
         handleClick(){
             this.refs.myTextInput.focus()
         }
        
         render(){
             return(
                <div>
                  <input type="text" ref="myTextInput" />
                  <input type="button" value="Focus the text input" onClick={this.handleClick.bind(this)}/>
                </div>
             )
         }
     }
     ReactDOM.render(<HelloWorld/>,document.getElementById('div'))
</script>

比较简单不多说,其实我个人在vue中比较喜欢偏向vdom的操作,react还不熟悉!

上一篇下一篇

猜你喜欢

热点阅读