package.json
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
}
npm start
启动开发环境,npm run build
创建生产环境优化代码,npm test
用于测试单元,npm run eject
把潜藏在react-scripts中的一序列技术栈“弹射”到
应用的顶端,此命令不可逆且会改变和增加一些文件。
data-*
;function Demo(){ const name = 'jsx'; const arr = [ <h3 key = {0}>数组</h3> <p key = {1}>数组会自动展开,注意添加key属性</p> ]; const func = () => { let result = 'hello'; if (name){ result += name; } else { result += 'world'; } return result; }; return ( <div> <h2></h2> {/*注释*/} <p style = {{color: 'red',fontSize: '14px'}}>hello {name || 'world'}</p> <p className = {name ? 'classA' : 'classB'}> hello {name && 'world'} </p> <p> {func()} </p> {arr} </div> ) }
this.prop
赋值是React.Component
构造函数的工作之一;super
调用父类也就是React.Component
的构造函数;super(props)
,那么组件实例被构造之后,类实例的所有成员就无法通过this.props
访问到父组件传递过来的props
值。class Child extends Component{ constructor(props){ super(props); this.state = { //获取外部传入的prop,并用于state初始化 count: props.initValue || 0, caption: props.caption } } }
React.PropTypes.*
,需导入prop-types
即安装:npm install prop-type --save
导入import PropTypes from ('prop-types')
PropTypes.node
PropTypes.element
PropTypes.instanceOf(Message)
PropTypes.oneOf(['News','Photos'])
PropTypes.oneOfType([
PropTypes.string,
PropTypes.number,
PropTypes.instanceOf(Message)
])
PropTypes.arrayOf(PropTypes.number)
PropTypes.objectOf(PropTypes.number)
PropTypes.func.isRequired
eg:
Child.propTypes = {
initValue: PropTypes.number,
caption: PropTypes.string
}
this.state
this.setState({})
注意:不要直接修改this.state的值,虽然能够改变组件的内部状态,但只是野蛮的修改了state,却不会驱动组件从新渲染,所以变化不会反应到界面
而,this.setState()
所做的事是先改变this.state
的值,然后驱动组件更新
eg: 父组件
class Parent extends React.Component{
getChildContext(){
return {color: "red"}
}
render(){
return(
<div>
<Child />
</div>
)
}
}
Parents.childContextTypes = {
color: PropTypes.string.isRequired
}
(有状态)子组件:
class Child extends React.Component{
render(){
return(
<div>
<p style = {{color:{this.context.color}}}>有状态的组件可以通过this.context获取</p>
<Grandchild />
</div>
)
}
}
Child.contextTypes = {
color: PropTypes.string.isRequired
}
(无状态)孙子组件:
function Grandchild(context){
return(
<p style = {{color: {context.color}}}>无状态组件可以直接在函数的参数中获取</p>
)
}
Grandchild.contextTypes = {
color:PropTypes.string.isRequired
}
不积跬步,何以行千里