修改this指向
- bind 方式綁定
- 函數通過箭頭函數進行創建
- constructor提前綁定
- 把事件的調用寫成箭頭函數的調用方式
<div id="reactDom"></div>
<script type="text/babel">
class Com extends React.Component {
constructor(props){
super(props)
this.myRef = React.createRef();
this.func = this.func.bind(this)
}
funa(){
console.log(this)
}
funb = ()=>{
console.log(this)
}
func(){
console.log(this)
}
fund(){
console.log(this)
}
fune=(i,e)=>{
console.log(i)
console.log(e)
}
render() {
return (
<div>我是組件
<button onClick={this.funa.bind(this)}>bind方式綁定</button>
<button onClick={this.funb}>箭頭函數綁定</button>
<button onClick={this.func}>提前綁定</button>
<button onClick={()=>{this.fund()}}>調用方式爲箭頭函數</button>
<h1>函數實參傳遞</h1>
<button onClick={this.fune.bind(this,"我是參數")}>點我傳遞實參</button>
<button onClick={(e)=>{this.fune("我是參數2",e)}}>點我傳遞實參</button>
</div>
)
}
}
ReactDOM.render(<Com />, document.getElementById("reactDom"))
</script>
條件渲染
條件渲染 — 根據狀態的變化只渲染其中的一部分
基本使用
<div id="reactDom"></div>
<script type="text/babel">
// 條件渲染 --- 根據狀態的變化只渲染其中的一部分
// if語句 jsx中不允許有if
class Com extends React.Component {
constructor(props) {
super(props)
this.state = {
bool: true
}
}
fun() {
this.setState({
bool:!this.state.bool
})
}
render() {
let text;
if (this.state.bool) {
text = "你好"
} else {
text = "你壞"
}
return (
<div>
我是組件
<button onClick={this.fun.bind(this)}>點我</button>
{text}
<p>三元運算法: {this.state.bool?"呵呵":"哈哈"}</p>
</div>
)
}
}
ReactDOM.render(<Com />, document.getElementById("reactDom"))
</script>
狀態提升
- 當多個組件需要同一個變化的數據時,需要把該數據提升到它們的父組件
- 多個組件需要利用到對方的狀態的情況下,就需要使用狀態提升
<div id="reactDom"></div>
<script type="text/babel">
class Demoa extends React.Component {
constructor(props) {
super(props)
}
render() {
return (
<div>
我是第一個組件 -- {this.props.text}
</div>
)
}
}
class Demob extends React.Component {
constructor(props) {
super(props)
}
render() {
return (
<div>
我是第二個組件 -- {this.props.text}
</div>
)
}
}
class Com extends React.Component {
constructor(props) {
super(props)
this.state={
comtext:"我是兩個人都想使用的數據"
}
}
fun=()=>{
this.setState({
comtext:"修改數據"
})
}
render() {
return (
<div>
我是組件
<button onClick={this.fun}>修改數據</button>
<Demoa text={this.state.comtext}/>
<Demob text={this.state.comtext}/>
</div>
)
}
}
ReactDOM.render(<Com />, document.getElementById("reactDom"))
</script>