获取原生的DOM
注意:获取DOM是要在组件渲染之后才能被获取,所以在constructor里面获取不到原生的DOM
方法一:回调函数 推荐
方法二:createRef() 16版本,推荐
方法三:ref 15版本,不推荐
import React,{Component,createRef} from 'react'; export default class Study extends Component { constructor(props){ super(props); this.oSpan = createRef(); this.oH = createRef(); } render(){ return ( <div> <p ref={el=>this.oP = el}>我是父级1</p> <span ref={this.oSpan}>我是父级1</span> <h1 ref={this.oH}>我是父级1</h1> <em ref='oEm'>我是父级1</em> </div> ) } componentDidMount(){ console.log('p标签',this.oP); console.log('span标签',this.oSpan.current); console.log('h标签',this.oH.current); console.log('em标签',this.refs.oEm); } }
组件的受控
受控的意思:页面的修改是通过state的修改的,是通过react来修改的。
栗子:获取input标签里面的value,显示在页面上。
方法一:不受控的方法,input标签不加value属性就是不受控的。首先获取原生的DOM,将原生的DOM
方法二:受控的方法,input标签加value属性就是受react控制的
import React,{Component,createRef} from 'react'; export default class Myinput extends Component { constructor(props){ super(props); this.state = { value1:'', value2:'' } } //第一种方法 changeInput1=()=>{ console.log(this.oInput.value) //获取原生的input节点,获取节点下面的value属性 this.setState({ value1: this.oInput.value }); } //第二种方法 changeInput2=(ev)=>{ console.log(ev.target.value) this.setState({ value2: ev.target.value }); } render(){ let {value1,value2} = this.state; return ( <div> <input onChange={this.changeInput1} ref={el=>this.oInput = el} type='text'/> <p >我是父级1dddd{value1}</p> <p>——————————</p> <input onChange={this.changeInput2} type='text' value={value2}/> <p >我是父级1dddd{value2}</p> </div> ) } }
兄弟组件的交流——通过回调函数
流程:
栗子:同一个父组件,下面两个子组件,一个组件点击按钮改变msg,里一个子组件显示改变之后的msg
import React,{Component,createRef} from 'react'; export default class Sibling extends Component { constructor(props){ super(props); this.state = { msg: '初始值' } } //点击按钮,修改值 changeMsg=()=>{ this.setState({ msg: this.siblingInput.value }) this.siblingInput.value = ''; } render(){ let {msg} = this.state; //点击send按钮,执行方法changeMsg,将input里面的value赋值给msg return ( <div> 兄弟组件交流 <p>————————</p> <Receive msg={msg}/> <p>————————</p> <Input getInput={el=>this.siblingInput = el}/> <Send changeMsg={this.changeMsg}/> <p>————————</p> </div> ) } } //接收信息 function Receive(props){ console.log(1,props) return( <div> 接收信息: {props.msg} </div> ) } //发送信息 function Send(props){ return( <div> 发送信息: <button onClick={()=>props.changeMsg(Math.random())}>send</button> </div> ) } //输入信息 function Input(props){ return( <input type='text' ref={props.getInput}/> ) }