一·、state
React 把组件看成是一个状态机,通过与用户的交互,实现不同状态,然后渲染 UI,让用户界面和数据保持一致。相当于vue2中的data
class Person extends React.Component{
state = { //定义方法一
boxClass:'yellow'
}
//constructor(props) {
// super(props);
// this.state = {date: new Date()}; //定义方法二
//}
switchStyle = ()=>{
let className = this.state.boxClass == 'yellow'?'red':'yellow'
this.setState({ //改变状态 重新render
boxClass:className
})
}
render(){
return (
<div onClick={this.switchStyle}>
{this.state.boxClass}
</div>
)
}
}
//创建添加到div中
ReactDOM.render(<Person/>,document.getElementById('test'))
二、props
state 和 props 主要的区别在于 props 是不可变的,而 state 可以根据与用户交互来改变。这就是为什么有些容器组件需要定义 state 来更新和修改数据。 而子组件只能通过 props 来传递数据。
class Person extends React.Component{
render(){
let name = this.props.name //得到标签中对应的name属性值
return (
<div>
{name}
</div>
)
}
}
//在标签中定义标签属性
ReactDOM.render(<Person name='张三'/>,document.getElementById('test'))
props校验,它可以保证我们的应用组件被正确使用,规范传值
class Person extends React.Component{
//对标签属性进行类型、必要性的限制
static propTypes = {
name:PropTypes.string.isRequired, //限制name必传,且为字符串
fn:PropTypes.func //函数类型 有点特殊
}
static defaultProps = { //默认值
name:'李四'
}
render(){
let name = this.props.name //得到标签中对应的name属性值
return (
<div>
{name}
</div>
)
}
}
//在标签中定义标签属性
ReactDOM.render(<Person name='张三'/>,document.getElementById('test'))
三、refs
获取dom元素
1.、字符串形式
//创建组件
class Demo extends React.Component{
//展示左侧输入框的数据
showData = ()=>{
const {input} = this.refs
console.log(input.value)
}
render(){
return(
<div>
<input ref="input" type="text" placeholder="点击按钮提示数据"/>
<button onClick={this.showData}>点击</button>
</div>
)
}
}
//渲染组件到页面
ReactDOM.render(<Demo/>,document.getElementById('test'))
2、回调函数形式(缺点,会调用两次,因为改变值后)
//创建组件 方式一 会调用两次
class Demo extends React.Component{
//展示左侧输入框的数据
showData = ()=>{
const {input1} = this
console.log(input1.value)
}
render(){
return(
<div>
<input ref={context => this.input1 = context} type="text" placeholder="点击按钮提示数据"/>
<button onClick={this.showData}>点击</button>
</div>
)
}
}
//渲染组件到页面
ReactDOM.render(<Demo/>,document.getElementById('test'))
//方式二 调用一次
class Demo extends React.Component{
//展示左侧输入框的数据
showData = ()=>{
const {input1} = this
console.log(input1.value)
}
saveInput = (c)=>{
this.input1 = c; //添加到原型上
console.log(c);
}
render(){
return(
<div>
{/*<input ref={context => this.input1 = context} type="text" placeholder="点击按钮提示数据"/>*/}
<input ref={this.saveInput} type="text"/><br/><br/>
<button onClick={this.showData}>点击</button>
</div>
)
}
}
//渲染组件到页面
ReactDOM.render(<Demo/>,document.getElementById('test'))
3、React.createRef,该容器可以存储被ref所标识的节点,唯一的,一个容器只能存储一个节点
//创建组件
class Demo extends React.Component{
myRef = React.createRef()
//展示左侧输入框的数据
showData = ()=>{
alert(this.myRef.current.value);
}
render(){
return(
<div>
<input ref={this.myRef} type="text" placeholder="点击按钮提示数据"/>
<button onClick={this.showData}>点我提示左侧的数据</button>
</div>
)
}
}
//渲染组件到页面
ReactDOM.render(<Demo a="1" b="2"/>,document.getElementById('test'))