组件定义每个单词的首字母要大写
在APP.js里调用
import PropsTest from './propsTest';
以及在render函数里调用子组件
render() { return ( <View style={styles.container}> <PropsTest name="熊爱明" /> </View> ); }
在子组件里申明
export default class PropsTest extends Component{ render () { return <Text style={{fontSize:20,backgroundColor:'red'}}>Hello+{this.props.name}</Text> } }
传递默认属性
在propsTest.js
别忘记加
static修饰符
export default class PropsTest extends Component{ 设置默认属性 static defaultProps={ name:'小红'} render () { return <Text style={{fontSize:20,backgroundColor:'red'}}>Hello+{this.props.name}</Text> } }
前提没有在APP.js里申明变量
对变量的属性检查
首先先下载
npm install prop-types --save字体库包
引入
import PropsTest from './propsTest';
static propTypes={ name:String }
static propTypes={ name:String, age:Number, sex:PropTypes.string.isRequired }
<Text style={{fontSize:20,backgroundColor:'red'}}>Hello+{this.props.sex}</Text>
延展操作符
var p={name:'王依米', age:16, sex:'女'} return ( <View style={styles.container}> <PropsTest name={p.name} age={p.age} sex={p.sex} // name='王依米' // age={16} // sex='女' /> </View> ); }
var p={name:'王依米', age:16, sex:'女'} return ( <View style={styles.container}> <PropsTest //延展操作符 {...p} // name={p.name} // age={p.age} // sex={p.sex} // name='王依米' // age={16} // sex='女' /> </View> ); }
{...p} 一下就把属性传递过去了
{/*{...p}*/}不是被注销的意思
state的应用
export default class State extends Component{ state ={ size:80 } constructor (props) { super(props); } render () { return ( <View> <Text style={{fontSize:20}} onPress={() =>{ this.setState({ size:this.state.size+10 }) }} >吹</Text> <Text style={{fontSize:20}} onPress={() =>{ this.setState({ size:this.state.size-10 }) }} >fang</Text> <Image style={{ width:this.state.size,height:this.state.size}} source={require('./timg.jpg')} /> </View>)http://www.devio.org博客