react详解state、props、refs
state ?state顾名思义就是状态,它只是用来控制这个组件本身自己的状态,我们可以用state来完成对行为的控制、数据的更新、界面的渲染,由于组件不能修改传入的props,所以需要记录自身的数据变化。 ?那么,我们要如何修改state中的值呢? setState? 时react用来修改state状态中的值的方法 如何使用 this.setState({ key:value })?? 这样就行了。 props ?react中说的单向数据流值说的就是props,根据这一特点它还有一个作用:组件之间的通信。props本身是不可变的,但是有一种情形它貌似可变,即是将父组件的state作为子组件的props,当父组件的state改变,子组件的props也跟着改变,其实它仍旧遵循了这一定律:props是不可更改的。 props一定来源于默认属性或者通过父组件传递而来,以下是这个写法: 1 static propProps = { 2 val:PropTypes.string.isRequired 3 } 4 static defaultProps = { 5 val:0 6 } 如果你觉得还是搞不清 state 和 props 的使用场景,那么请记住一个简单的规则:尽量少地用 state,尽量多地用 props。 没有 state 的组件叫无状态组件(stateless component),设置了 state 的叫做有状态组件(stateful component)。因为状态会带来管理的复杂性,我们尽量多地写无状态组件,尽量少地写有状态的组件。这样会降低代码维护的难度,也会在一定程度上增强组件的可复用性。函数式组件就只有props没有state,而react也非常鼓励我们编写函数式组件。 以下给props和state做一个总结:
组件的state相当于组件的记忆,其存在的意义就是被修改,每一次通过setState函数修改state就改变了组件的状态,然后通过把渲染过程体现出来。但是组件的props绝不应该被修改,我们可以想象一个场景,一个父组件将同一个props传给几个子组件,若有一个子组件将props修改,那么其他的组件就不一定能得到自己想到的值,此时的情况将混乱不堪。 refs 某些情况下需要直接修改元素,要修改的子代可以是 React 组件实例,也可以是 DOM 元素。这时就要用到refs来操作DOM。 ref??React 支持给任意组件添加特殊属性ref ,ref可以是一个字符串,也可以是一个属性接受一个回调函数,它在组件被加载或卸载时会立即执行。 新ref??版本16.3 之前,React 有两种提供? 1 class MyComponent extends React.Component { 2 constructor(props) { 3 super(props); 4 this.myRef = React.createRef(); 5 } 6 render() { 7 return <div ref={this.myRef} />; 8 } 9 } ? ??然后使用 1 this.myRef.current ? [注意]使用 1 <Wrap innerRef={this.itemRef}> ? ref传递原理??当给 HTML 元素添加 1 class CustomTextInput extends React.Component { 2 constructor(props) { 3 super(props); 4 this.focus = this.focus.bind(this); 5 } 6 focus() { 7 this.textInput.focus(); 8 } 9 render() { 10 return ( 11 <div> 12 <input 13 type="text" 14 ref={(input) => { this.textInput = input; }} /> 15 <input 16 type="button" 17 value="Focus the text input" 18 onClick={this.focus} 19 /> 20 </div> 21 ); 22 } 23 } ? 更简短的写法如下: 1 ref={input => this.textInput = input} ? 类组件??当· class AutoFocusTextInput extends React.Component { componentDidMount() { this.textInput.focusTextInput(); } render() { return ( <CustomTextInput ref={(input) => { this.textInput = input; }} /> ); } } ? [注意]这种方法仅对 class 声明的? 函数式组件不能在函数式组件上使用 ref 属性,因为它们没有实例。 对父组件暴露DOM节点??在子节点上暴露一个特殊的属性。子节点将会获得一个函数属性,并将其作为 ref 属性附加到 DOM 节点。这允许父代通过中间件将 ref 回调给子代的 DOM 节点。 1 function CustomTextInput(props) { 2 return ( 3 <div> 4 <input ref={props.inputRef} /> 5 </div> 6 ); 7 } 8 9 class Parent extends React.Component { 10 render() { 11 return ( 12 <CustomTextInput 13 inputRef={el => this.inputElement = el} 14 /> 15 ); 16 } 17 } ? ??在上面的例子中, 参考链接 :https://www.jianshu.com/p/2f6d81a15d81 ?https://www.jianshu.com/p/628d5514b145 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |