近期学习了一下react框架,想在这里整理一下不熟和不怎么理解的知识点
this.props.children
this.props 对象的属性与组件的属性一一对应,但是有一个例外,就是 this.props.children 属性。它表示组件的所有子节点,其值有三种可能:如果当前组件没有子节点,它就是 undefined ;如果有一个子节点,数据类型是 object ;如果有多个子节点,数据类型就是 array
<div id="box"></div>
<script type="text/babel">
var App=()=>({
render: function() {
console.log(this.props.children)
return " Hello Rect"
}
});
var App1=()=>({
render: function() {
console.log(this.props.children)
return " Hello Rect"
}
});
var App2=()=>({
render: function() {
console.log(this.props.children)
return " Hello Rect"
}
});
ReactDOM.render(
<div><App></App><App1><span>Hello</span></App1><App2><span>Hello</span><span>Rect</span></App2></div>,document.getElementById('box')
);
PropTypes
组件的属性可以接受任意值,字符串、对象、函数,所以需要一种机制,验证别人使用组件时,提供的参数是否符合要求。
组件类的PropTypes属性,就是用来验证组件实例的属性是否符合要求
如果此时设置title属性为string类型,而传递的参数为number,则会报错
安装npm install prop-types --save
引入import PropTypes from ‘prop-types’;
var App=()=>({
propTypes: {
title: React.PropTypes.string.isRequired,
},
render: function() {
return this.props.title
}
});
var data = 2333;
ReactDOM.render(
<App title={data}></App>,document.getElementById('box')
);
defaultProps
如果父组件调用子组件的时候不给子组件传值,可以在子组件中使用defaultProps定义的默认值
refs标识符使用的三种方法
方法一
<input type="text" ref="txt"/>
this.refs.txt.focus()找到该节点
class App extends React.Component{
componentDidMount(){
console.log(this.refs.txt)
}
render(){
return <div>
<input type="text" ref="txt" />
</div>
}
}
ReactDOM.render(<App/>,document.getElementById("box"));
方法二
<input type="text" ref={(node)=>this.txtNode=node}/>
this.txtNode.focus()找到该节点
class App extends React.Component{
componentDidMount(){
console.log(this.node)
}
render(){
return <div>
<input type="text" ref={(node)=>{this.node=node}} />
</div>
}
}
ReactDOM.render(<App/>,document.getElementById("box"));
方法三
this.state={ 变量: createRef() }
<node ref={this.state.变量} />
引用这个节点 this.state.变量.current 就可以引用这个节点了
import React, { Component,createRef } from 'react'
export default class index extends Component {
//ref 字符串 回调函数 createRef
constructor(props){
super(props);
this.state ={
node:createRef()
}
}
componentDidMount(){
console.log(this.state.node.current.value)
}
render() {
return (
<div>
<input type="text" defaultValue="111" ref={this.state.node} />
<label htmlFor="flag">flag</label>
<input id="flag" type="checkbox" defaultChecked />
</div>
)
}
}