react ( 二 )

时间:2023-01-21 23:33:45

ref属性

  • 当我们在 react组件中要访问真实的DOM元素时,你可能需要用到ref属性,ref接收一个函数作为属性值,函数接收一个参数,这个参数就是真实的DOM元素。真实的DOM元素渲染到页面上之后,ref函数就会执行。

ReactDOM.render(
<div>
<input
{/* 这里的el就是原生的input元素 */}
ref={ (el)=> console.log( el ) }
/>
</div> ,
root );
  • ref属性也可以用在react组件上面,用在组件上时,ref函数接收的参数是组件的实例,(但是不建议这样做)。


ReactDOM.render(
<div>
<input
{/* 这里的el就是原生的input元素 */}
ref={ (el)=> console.log( el ) }
/>
</div> ,
root );
  • 当父组件需要获取子组件的DOM元素时,我们也可以利用 ref 接收父组件传的,把元素绑定到父组件
class App extends Component {
constructor(props) {
super(props);
this.child = null;
} logEl = ()=>{ console.log( this.child ); //打印子组件的input元素
} render(){
return (
<div>
{/* 传一个函数给子组件 */}
<Child
getEl={ (el)=> this.child = el }
/>
<button
onClick={ logEl }
>获取子组件元素</button>
</div>
);
}
} class Child extends Component{ constructor(props) {
super(props);
} render(){ let {getEl} = this.props; return (
<div>
{/* 子组件的元素用ref接收父组件传来的函数,元素渲染到页面时,就绑定到了父组件的属性上面 */}
<input
ref={ getEl }
type="text"/>
</div>
);
}
};

组件受控和不受控

  • 受控:

    组件的状态变化,是 react 控制的 (大多数时候, 接受 state 和 props 的控制)
  • 不受控:

    某些组件, 比如 input, select 这种组件,状态的变化可能是控件本身具有功能, 它状态的变化,并不是 react 控制的

    让这类组件受控很简单:给一个 value 的属性, 这个时候,react 就接管了这个组件

默认参数 defaultProps

给属性声明默认值 , 值是 undefined 的时候才会启用

class App extends Component{
constructor(props){
super(props);
this.bb = 8;
} // 默认参数: es6 的写法
static defaultProps = {
a: 'a 没有传',
b: 'b 没有传',
c: 'c 没有传',
d: 'd 没有传'
} render(){
let {a,b,c,d} = this.props;
return (
<div>
<ul>
<li>{a}</li>
<li>{b}</li>
<li>{c}</li>
<li>{d}</li>
</ul>
</div>
)
}
} //react的写法
// App.defaultProps={
// a: 'a 没有传',
// b: 'b 没有传',
// c: 'c 没有传',
// d: 'd 没有传'
// };

参数类型检测:propTypes



class App extends Component{
constructor(props){
super(props);
} render(){
let {a,b,c,d} = this.props;
return (
<div>
<ul>
<li>a是字符串:{a}</li>
<li>b是数字:{b}</li>
<li>c是函数:{c()}</li>
</ul>
<p>{d.a}:{d.b}</p>
</div>
)
}
} App.propTypes = {
a: PT.string,
b: PT.number.isRequired,
c: PT.func.isRequired,
d: PT.shape({
a: PT.string.isRequired,
b: PT.number.isRequired
})
}
App.defaultProps = {
b: '88879',
c: f=>f,
d: {}
} ReactDOM.render(
<div>
<App
a="aaa"
b={12499}
c={ ()=><p>ppppp</p> }
/>
<br/>
<App
a="aaa"
// b={12499}
c={ ()=><p>ppppp</p> }
/>
<br/>
<App
a="aaa"
b={12499}
d={{
a: 'dfsj',
b: 999
}}
/>
<br/>
</div>
,
document.getElementById('root')
); // 对开发有帮助
// 在开发的阶段用, 上线的时候需要移除验证的代码
// 默认属性也会参与数据验证