第十一天罗~
昨天我们说到 state
, 那我们如何去改变 state
呢?
当我们直接改动 state
, 会发现, 画面根本不会更新
like:
class App extends React.Component {
constructor() {
super();
this.state = {
text: 'hello',
};
}
onPressClickMe = () => {
this.state.text = 'Wow~';
};
render() {
return (
<SafeAreaView>
<View>
<Button title='Click Me!!' onPress={this.onPressClickMe} />
<Text>{this.state.text}</Text>
</View>
</SafeAreaView>
);
}
}
state
的改变需要跟随着 component
的更新流程,这样才会把更新的数据显示在画面上
那如何触发更新流程呢?
更新指定 state
, 并触发 component
的 update 的流程
this.setState(updater, [callback]);
当下
的 state & props ,可以以此为参考基础来进行更新, return object
包裹需要更改的值callback
会在更新流程结束後去执行//object
this.setState({ text: 'hello!' });
//function
this.setState(function (state, props) {
return {
text: 'hello',
};
});
//use callback
this.setState(
function (state, props) {
return {
text: 'hello',
};
},
function () {
console.log(this.state);
}
);
所以,我们希望画面随着我们 state
值改变而改变,应该这样做...
like:
class App extends React.Component {
constructor() {
super();
this.state = {
text: 'hello',
};
}
onPressClickMe = () => {
this.setState(() => {
return {
text: 'Wow~',
};
});
};
render() {
return (
<SafeAreaView>
<View>
<Button title='Click Me!!' onPress={this.onPressClickMe} />
<Text>{this.state.text}</Text>
</View>
</SafeAreaView>
);
}
}
当 component
内部进行更新流程的时候,
就会把底下有使用到的 component
一起更新
再来谈到 props
,
当我们在开发时,总会考虑到 component 会在不同的情境上使用,
但是不可能把所有的逻辑都写在 component 里面,
这时我们就必须去靠 props
来让外部有部分的控制权限 ,
那它的特性是:
能够多大程度
去间接影响 component
的运作props
属性里,以物件key-value
保存props
props
值,只有在外部传入的值发生改变时component
的 update 流程
const TextBox = () => {
return <Text>{this.props.value}</Text>;
};
const App = () => {
return (
<SafeAreaView>
<TextBox value={'Hello'} />
</SafeAreaView>
);
};
<<: 30-11 之Domain Layer - Transaction Script
资讯安全管理制度(ISMS)相关文件属於企业或机构内部资安治理运行标准与纪录,机密等级(控管标准)大...
“In man's struggle against the world, bet on the ...
相信这个问题做了几年工程师之後,应该多少都有想过一两次吧? 在管理职当然做的事情,就会从面对事情而转...
最近看了很多好书,看完的共通感想是,为什麽以前没人推荐我看这些?如果早点看,不知道可以少走多少弯路。...
出於书本 Chapter 1. Introduction to Ethical Hacking 骇客...