父传子:
父:
import React, { Component } from 'react'
export default class navbar extends Component {
render() {
let { title,leftShow,rightShow } = this.props;
//属性是父组件传来的,this.props
return (
<div>
{leftShow? <button>left</button> : null}
<span>{title}</span>
{rightShow&&<button>right</button>}
</div>
)
}
}
子:
import React, { Component } from 'react'
import Navbar from './Navbar/index'
export default class App extends Component {
render() {
return (
<div>
<h1>首页</h1>
<Navbar title='首页' leftShow={false} rightShow={false}/>
<h1>列表</h1>
<Navbar title='列表' leftShow={true} rightShow={false}></Navbar>
<h1>购物车</h1>
<Navbar title="购物车" leftShow={true} rightShow={true}></Navbar>
</div>
)
}
}
属性验证:
import React, { Component } from 'react'
import propTypes from 'prop-types'
export default class navbar extends Component {
// 类属性
static propTypes = {
title: propTypes.string,
leftShow: propTypes.bool,
rightShow: propTypes.bool
}
render() {
let { title, leftShow, rightShow } = this.props;
//属性是父组件传来的,this.props
return (
<div>
{leftShow ? <button>left</button> : null}
<span>{title}</span>
{rightShow && <button>right</button>}
</div >
)
}
}
/*navbar.propTypes = {
title: propTypes.string,
leftShow: propTypes.bool,
rightShow: propTypes.bool
} */
默认值:
import React, { Component } from 'react'
import propTypes from 'prop-types'
export default class navbar extends Component {
// 类属性
static propTypes = {
title: propTypes.string,
leftShow: propTypes.bool,
rightShow: propTypes.bool
}
static defaultProps = {
title: '首页',
leftShow: true,
rightShow: true
}
render() {
let { title, leftShow, rightShow } = this.props;
//属性是父组件传来的,this.props
return (
<div>
{leftShow ? <button>left</button> : null}
<span>{title}</span>
{rightShow && <button>right</button>}
</div >
)
}
}
// 默认值
/*navbar.defaultProps = {
title: '首页',
leftShow: true,
rightShow: true
}*/
简写:
import React, { Component } from 'react'
import Navbar from './Navbar/index'
export default class App extends Component {
render() {
var obj = {
title: "购物车",
leftShow: true,
rightShow: false
}
return (
<div>
<h1>首页</h1>
<Navbar />
<h1>列表</h1>
<Navbar title='列表' leftShow={true} rightShow={false}></Navbar>
<h1>购物车</h1>
<Navbar {...obj}></Navbar>
</div>
)
}
}
props函数式组件:
import React from 'react'
export default function Siderbar(props){
let {bg}=props
return (
<div>
<ul style={{background:bg}}>
<li>1111111111111111</li>
</ul>
</div>
)
}
属性vs状态 属性(Props)状态(State)
相似点:都是纯js对象,都会触发render更新,都有确定性(状态/属性相同,结果相同)
不同点:
- 属性能从父组件中获取,状态不能
- 属性可以在父组件中修改,状态不能
- 属性能从内部设置默认值,状态也可以,设置方式不一样
- 属性不在组件内部修改,状态要在组件内部修改
- 属性能设置子组件的初始值,状态不可以
- 属性可以修改子组件的值,状态不可以
相关作者
- 获取点赞0
- 文章阅读量264
评论()