state
什么是state
state
是状态
state
和props
的区别
props
是组件对外部的接口,如果子组件需要使用父组件的数据就可以通过props
来进行数据传递,
state
是组件对内的接口,组件自身可能有需要管理的数据,对管理数据的属性就是state
如果需要使用state 不能使用无状态组件
class MyComponent extends React.Component {
constructor(props) {
super(props)
// state是可变的,props 是只读的
this.state = {
name : "react"
}
}
// this.setState({key:value}) 是异步的,react 就会自动触发render进行数据的渲染
render(){
return ( <div>我是组件
<button onClick= {
()=>{
this.setState({
name:"vue"})}}>changeValue</button>
<div></div>
name :{
this.state.name}
</div> )
}
}
refs
refs
: react
当中提供了一个refs
的数据 不能再无状态组件当中进行使用 因为无状态组件没有实例
表示当前组件的真正实例的引用 他会返回当前属性的元素
标识组件内部的元素
官方建议不要过度使用refs
需要优先考虑state
refs三种方式使用
- 字符串
class MyComponent extends React.Component {
fun = ()=>{
console.log(this.refs.demoInput.value)
}
render (){
return ( <div>
我是一个组件
<input type="text" ref="demoInput " placeholder = "请输入"/>
<button onClick = {
this.fun} >click me to get value</button>
</div> )
}
}
ref
回调函数就是在dom
节点上或者组件上挂载函数 函数的入参是dom 节点
class MyComponentB extends React.Component {
fun = ()=>{
console.log(this.inputValue.value)
}
render (){
return ( <div>
我是一个组件 回调
<input type="text" ref={
(input)=>{
this.inputValue = input}} placeholder = "请输入"/>
<button onClick = {
this.fun} >click me to get value</button>
</div> )
}
}
React.createRef()
(react
16.3新提供的方式)
// 把值付给一个变量,使用ref的current属性拿到这个节点
class MyComponentC extends React.Component {
constructor(props){
super(props)
this.myRef =React.createRef()
}
fun = ()=>{
console.log(this.myRef.current.value)
}
render (){
return ( <div>
我是一个组件 回调
<input type="text" ref={
myRef } placeholder = "请输入"/>
<button onClick = {
this.fun} >click me to get value</button>
</div> )
}
}