前言
上期介绍了react中两种组件的基本写法:
【react】初学react1-jsx、虚拟dom、组件渲染
一、state
state可以写在构造器中,也可以写在外面,构造器的写法比较麻烦,不推荐
class Weather extends React.Component{
// constructor(props){
// super(props)
// // this.state={isHot:true}
// // this.changeWeather=this.changeWeather.bind(this)
// }
// 初始化状态-state必须是对象
state={isHot:true}
render(){
// const {isHot}=this.state
return <h2 onClick={this.changeWeather}>今天天气{this.state.isHot?'hot':'cold'</h2>
}
changeWeather=()=>{
// changeWeather方法放在了类的原型对象上,供实例使用;
// 由于该方法是作为onclick的回调,是直接调用,不是通过实例调用的
// 类中的方法默认开启局部严格模式,所以该方法中的this为undefined
const isHot=this.state.isHot
this.setState({isHot:!isHot})
}
}
ReactDOM.render(<Weather/>,document.getElementById('test'))
提示:
react将js中所有原生onxx事件都重写了,onclick->onClick,onblur->onBlur,注意大小写
状态不能直接更改,必须用setState更新
二、props
注意:props是只读的
如果增加限制,需要额外再引入prop-types文件。对props的限制可以写在类内也可以写在类外,对标签属性进行类型、必要性限制。
类内通过static propTypes={}的形式添加限制,static defaultProps={}指定默认值;
类外通过类名.propTypes={}得形式添加限制, Person.defaultProps={}指定默认值。
<!-- 引入prop types用于对组件标签进行限制 -->
<script type="text/javascript" src="../js/prop-types.js"></script>
1.类式组件使用props
完整案例代码如下:
class Person extends React.Component{
// 类中的构造器能省略就省略
// constructor (props){
// // 构造器是否接受props传递给supper,取决于是否希望在构造器中通过this访问props
// super(props)
// }
state={}
static propTypes={
name:PropTypes.string.isRequired,//isRequired必须传递的参数
sex:PropTypes.string,
speak:PropTypes.func//函数类型
}
static defaultProps={
sex:'nono',
age:18
}
render(){
const {name,age,sex}=this.props
return (
<ul>
<li>name:{name}</li>
<li>age:{age}</li>
<li>sex:{sex}</li>
</ul>
)
}
}
// Person.propTypes={
// name:PropTypes.string.isRequired,//isRequired必须传递的参数
// sex:PropTypes.string,
// speak:PropTypes.func//函数类型
// }
// // 指定标签默认值
// Person.defaultProps={
// sex:'nono',
// age:18
// }
ReactDOM.render(<Person name='tom' age={18} sex="female" speak={speak}/>,document.getElementById('test'))
const p2={name:'tom2', age:"128", sex:"female2"}
ReactDOM.render(<Person {...p2} />,document.getElementById('test2'))
function speak(){
console.log('props speak---')
}
2.函数式组件使用props
function Person2(props){
const {name,age,sex}=props
return (
<ul>
<li>name:{name}</li>
<li>age:{age}</li>
<li>sex:{sex}</li>
</ul>
)
}
Person2.propTypes={
name:PropTypes.string.isRequired,
sex:PropTypes.string,
}
// 指定标签默认值
Person2.defaultProps={
sex:'nono',
age:55
}
ReactDOM.render(<Person2 name='tom3' sex="female" speak={speak}/>,document.getElementById('test3'))
总结
主要介绍了state与props的基础用法,学习中,后续会补充~
1234

被折叠的 条评论
为什么被折叠?



