React 基础 day02
绑定 this 并传值的几种方式
import React from 'react'
class BindThis extends React.Component {
constructor(props) {
super(props)
this.state = {
msg: '这是初始化的msg'
}
// 修改指向之後,再指向同一塊内存地址調用
this.inputChange2 = this.inputChange2.bind(this, '🚗', '🚓')
}
render() {
return <div>
<input type="button" value="第一种改变方式" onClick={inputChange1.bind(this, '😘', '😂')}>
<input type="button" value="第二种改变方式" onClick={inputChange2}>
{/* 使用箭頭函數,不會修改 this 的指向 */}
<input type="button" value="第三种改变方式" onClick={() => {this.inputChange3('🎆', '🎇')}}>
<hr/>
<div>{this.state.msg}</div>
</div>
}
// 通過 bind 改變 this 指向,再傳值
inputChange1(arg1, arg2){
this.setState({
msg: `${arg1} ---- ${arg2}`
})
}
inputChange2(arg1, arg2){
this.setState({
msg: `${arg1} ---- ${arg2}`
})
}
inputChange3(arg1, arg2){
this.setState({
msg: `${arg1} ---- ${arg2}`
})
}
}
为表单实现双向数据绑定
React 中默认不支持双向数据绑定
如果为表单元素, 提供value数据绑定, 那么必须同时为表单数据绑定 readOnly 属性 或者 onChange 事件
readOnly: 表示这个元素是只读的不能修改
onChange: 表示这个元素的值可以被修改, 但是要自己定义修改逻辑
class bind extends React.Component {
constructor(props) {
super(props)
this.state = {
msg: '这是初始的msg'
}
}
render () {
return <div>
<input type="text" style={{width: '100%'}} value={this.state.msg} readOnly/>
<input type="text" style={{width: '100%'}} value={this.state.msg} onChange={this.txtChanged} id="txt" ref="txt"/>
<div>{this.state.msg}</div>
</div>
}
// 使用箭头函数解决 this 指向问题
txtChanged = (e) => {
// 1. 使用 document.getElementById('txt').value
// 2. 使用 this.refs.txt.value
// 3. 使用 e.target.value
this.setState({
msg: this.refs.txt.value
})
}
}
context 特性
在 react 中 父组件向子组件传值, 可以通过 this.props 的方式传值, 但是如果有多层的话, 中间层不需要的时候, 这种方法就显示不是很实用了, 而 context 属性就是为了解决这个问题的 ;
import React from 'react'
import ReactTypes from 'prop-types'
class Com1 extends React.Component {
constructor(props) {
super(props)
this.state = {
color: 'red'
}
}
// 1. 在父组件中定义一个方法, 固定名称: getChildContext, 内部返回一个对象, 共享给所有子组件的数据
getChildContext () {
return {
color: this.state.color
}
}
// 2. 使用属性校验, 规定传递给子组件的数据类型, 需要一个 static childContextTypes (固定名称)
static childContextTypes = {
// 传递给子组件的类型
color: ReactTypes.string
}
render () {
return <div>
<h3>这是父组件</h3>
{/* <Com2 color={this.state.color}></Com2> */}
<Com2></Com2>
</div>
}
}
class Com2 extends React.Component {
render () {
return <div>
<h4>这是中间子组件</h4>
{/* <Com3 color={this.props.color}></Com3> */}
<Com3></Com3>
</div>
}
}
class Com3 extends React.Component {
// 3. 校验父组件传递过来的参数类型
static contextTypes = {
color: ReactTypes.string // 如果子组件想要使用context共享的数据, 使用之前一定要做类型校验
}
render () {
return <div>
{/* <h5 style={{color: this.props.color}}>这是末尾子组件</h5> */}
<h5 style={{color: this.context.color}}>这是末尾子组件</h5>
</div>
}
}