demo
https://gitee.com/zyzcos/react-study
博客
https://zyzcos.gitee.io/
条件渲染
其实就是在组件内写
判断逻辑
进行条件渲染。
function FirstCome(props){
return <h1>Welcome , { props.name }</h1>
}
function UnFirstCome(props){
return <h1>Welcom back , { props.name }</h1>
}
function showWelcome(props){
const userName = props.name;
const isFirstTime = props.timeFlag;
if(isFirstTime){
return <FirstCome name = { userName } />
}else{
return <UnFirstCome name = { userName } />
}
}
有状态组件
个人理解:就是具有条件渲染的组件,称为状态组件。
// 根据上面的代码,创建一个具有状态的组件 BootScreen
function Introduce(props){
return <h1>这里是一个专注于分享的地方</h1>
}
function BootScreen(props){
const userName = props.name;
const FirstTime = props.timeFlag
// 进行条件渲染,将渲染结果存在元素welcome中
let welcome
if(isFirstTime){
welcome = <FirstCome name = { userName } />
}else{
welcome = <UnFirstCome name = { userName } />
}
// 进行组件的渲染返回
return (
<div>
<Introduce />
{ weclome }
</div>
)
}
JSX内联条件渲染
之前学JSX的时候就讲过,{}在其中可以书写JS逻辑代码,就此原理,可以在JSX模板内进行内联渲染
- 通过运算符
&&
实现
//构建一个消息未读的提示组件
function UnReadBox(props){
const unreadMessages = props.unreadMessages;
return(
<div>
{
unreadMessages.length > 0 &&
<h1>您有 { unreadMessage.length } 条信息未读</h1>
}
</div>
)
}
- 通过三目运算符
FLAG ? VALUE1 : VALUE2
实现
//构建一个消息未读的提示组件
function UnReadBox(props){
const unreadMessages = props.unreadMessages;
const unreadBox = <h1>您有 { unreadMessage.length } 条信息未读</h1>;
const normalBox = <h1>您暂无未读消息</h1>
return(
<div>
{
unreadMessages.length > 0 ? unreadBox : normalBox
}
</div>
)
}
阻止渲染
可以通过
return null
来阻止渲染。但是阻止渲染不会影响组件的生命周期。
下面通过一个显示和关闭未读消息的组件来测试一下
function UnReadBox(props) {
const isShow = props.isShow;
const unreadMessages = props.unreadMessages;
const unreadBox = <h1>您有{ unreadMessages.length }条信息未读</h1>;
const normalBox = <h1> 您暂无未读消息 </h1>
if(isShow){
if (unreadMessages.length > 0) {
return unreadBox;
} else {
return normalBox;
}
}else{
return null;
}
}
//用来控制是否显示未读盒子
class BoxControl extends React.Component {
constructor(props) {
super(props);
this.state = { showBox: true , message:['1','2','3','4'] };
this.handleToggleClick = this.handleToggleClick.bind(this);
this.handleClearMessage = this.handleClearMessage.bind(this);
}
// 是否显示未读盒子
handleToggleClick(){
this.setState(state=>({
showBox:!state.showBox
}));
}
// 清除未读消息
handleClearMessage(){
this.setState(state=>({
message:[]
}))
}
render(){
return(
<div>
<button onClick={ this.handleToggleClick }>
{ this.state.showBox ? '隐藏' : '显示' }
</button>
<button onClick={ this.handleClearMessage }>清除未读</button>
<UnReadBox
unreadMessages = { this.state.message }
isShow = { this.state.showBox }
/>
</div>
)
}
}
列表渲染
怎样渲染多个元素?
React的列表渲染,就是用类似于
map
的函数,将多个元素变量处理后,再存到一个新的元素变量中,从而完成列表渲染。
const movies = ['长津湖','铁道游击队','无尽'];
const movieElements = movies.map((movie)=>{
<li>{ movie }</li>
});
ReactDOM.rander(
<ul>{ movieElements }</ul>,
document.getElementById('root')
)
通常,我们会将这个
列表渲染
封装在组件内进行
class MoviesList extends React.Component {
constructor(props){
super(props);
const movies = props.movies;
}
render(){
const moviesList = movies.map( (movie,index) => {
<li key={ index }> { movie } </li>
});
return (
<ul> { moviesList } </ul>
)
}
}
根据个人理解,React应该是为了渲染的时候,能够准确定位到某个元素,所以需要给列表元素一个
key
作为标识。
key需要在兄弟内具有
唯一性
。但不需要具有全局唯一性
。与此同时key是不可读的
表单
受控组件?
控制着
用户输入
和数据的操作
的、渲染表单的React组件。
class NameForm extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event){
this.setState(
{ value:event.target.value }
)
}
handleSubmit(event){
alert('提交的名字: ' + this.state.value);
event.preventDefault();
}
render(){
return(
<form onSubmit = { this.handleSubmit }>
<label>
名字
<input type = 'text'
value = { this.state.value }
onChange = { this.handleChange }
/>
</label>
<input type='submit' value='提交'/>
</form>
)
}
}
由这些学习可以得知,State是React中的唯一数据源。
React控制select
标签
class FruitsSelection extends React.Component {
constructor(props) {
super(props);
this.state = {value: 'banana'}; // 默认选中的是苹果
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event){
this.setState(
{ value:event.target.value }
)
}
handleSubmit(event){
alert('你最喜欢的水果是: ' + this.state.value);
event.preventDefault();
}
render(){
return(
<form onSubmit = { this.handleSubmit }>
<label>
选择你喜欢的水果:
<select value={ this.state.value } onChange={ this.handleChange }>
<option value='apple'>苹果</option>
<option value='banana'>香蕉</option>
<option value='watermelon'>西瓜</option>
</select>
</label>
<input type='submit' value='提交'/>
</form>
)
}
}
有时候
受控组件
使用起来会觉得很繁琐,特别是不是纯React开发的项目中,所以官方推荐在非纯React项目中使用非受控组件
非受控组件
会在高级篇学到,目前先放一放
状态提升
什么是状态提升
其实也就是变量提升的意思,将
state
的作用域提升,从本组件,提升到父组件。从而使得兄弟及其子组件共享状态。
个人理解:估计就类似于父子组件通信吧
如何状态提升
// 父组件
function BoilingVerdict(props){
if(props.celsius >= 100){
return <p>水开了</p>
}else{
return <p>水还没有开</p>
}
}
const scaleNames = {
c: 'Celsius',
f: 'Fahrenheit'
};
// 两个convert函数
function toCelsius(fahrenheit) {
return (fahrenheit - 32) * 5 / 9;
}
function toFahrenheit(celsius) {
return (celsius * 9 / 5) + 32;
}
// 用于温度的转换
function tryConvert(temperature, convert) {
const input = parseFloat(temperature);
if (Number.isNaN(input)) {
return '';
}
const output = convert(input);
const rounded = Math.round(output * 1000) / 1000;
return rounded.toString();
}
class TemperatureInput extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
this.props.onTemperatureChange(e.target.value);
}
render() {
const temperature = this.props.temperature;
const scale = this.props.scale;
return (
<fieldset>
<legend>Enter temperature in {scaleNames[scale]}:</legend>
<input value={temperature}
onChange={this.handleChange} />
</fieldset>
);
}
}
// 子组件
class Calculator extends React.Component {
constructor(props) {
super(props);
this.handleCelsiusChange = this.handleCelsiusChange.bind(this);
this.handleFahrenheitChange = this.handleFahrenheitChange.bind(this);
this.state = {temperature: '', scale: 'c'}; //默认为摄氏度
}
handleCelsiusChange(temperature) {
this.setState({scale: 'c', temperature});
}
handleFahrenheitChange(temperature) {
this.setState({scale: 'f', temperature});
}
render() {
const scale = this.state.scale;
const temperature = this.state.temperature;
const celsius = scale === 'f' ? tryConvert(temperature, toCelsius) : temperature;
const fahrenheit = scale === 'c' ? tryConvert(temperature, toFahrenheit) : temperature;
return (
<div>
<TemperatureInput
scale="c"
temperature={celsius}
onTemperatureChange={this.handleCelsiusChange} />
<TemperatureInput
scale="f"
temperature={fahrenheit}
onTemperatureChange={this.handleFahrenheitChange} />
<BoilingVerdict
celsius={parseFloat(celsius)} />
</div>
);
}
}
ReactDOM.render(
<Calculator></Calculator>,
document.getElementById('root')
)
总结一下:状态提升,就是两个兄弟组件引用父组件的同一个状态,达到状态共享的效果。
组合与继承
组合 ——> 包含关系,飞机=机身+机翼+机头+机尾
继承 ——> 特殊到一半关系,动物 > 猫
包含关系
其实在学了React的时候,就会发现其基本就是组件元素,且组件元素可以存放在变量(在这里称之为
元素变量
)中。
在开发中,其实很多
盒子
里面不知道放什么,这样我们可以预留一个地方(类似于插槽
,但是React中没有这个概念)
然后我们可以通过
props
将元素变量
传递到这些留白
的地方,进而达到组合使用
的效果
function Component1(props){
return <h1>这里是组件1</h1>
}
function Component2(props){
return <h1>这里是组件2</h1>
}
function Nav(props){
return(
<div>
// 这里就是`留白`的地方
<div class="left-side">{ props.left }</div>
<div class="right-side">{ props.right }</div>
</div>
)
}
function App(props){
return(
// 通过props,将需要渲染的元素,传递给子组件,从而达到`组合使用`的效果
<Nav left={ <Component1 /> }
right={ <Component2 />}
>
)
}
特殊到一般关系
根据个人理解,其实就是传不同参数,响应不同的数据而已。
比如说同一个欢迎组件,当A访问就显示Hello!A。
B访问就显示Hello!B。
根据官方的说法,在FaceBook中,他们并没有发现需要使用继承
关系来构建组件层次的情况。
所以说,继承关系使非常非常罕见的
但是我又有另外一种理解,其实继承可以适用于
开发组件库
中。
比如说,开发一个组件:按钮
。别人使用的时候,为了代码的内部安全性,不被他人修改。
你就可以将其封装
起来。让别人使用的时候只能通过继承
,从而达到保护
的效果。
总结
React
的基础算是学完了,我感觉其中的概念和Vue.js相差不大,只有实现方式上的差别。
React
给我的感觉就是,貌似比较贴切JS。我个人的初步感觉就是:大多数都是使用了JS原生的东西。
就对于父子通信这方面来看,我觉得React
给我的感觉比Vue
的好,好像Vue
利用porps
完成父子通信的时候,有点复杂。也说不出个为什么,就是感觉。