美文网首页
React Native学习之props与state(一)

React Native学习之props与state(一)

作者: dhhuanghui | 来源:发表于2018-04-18 10:01 被阅读24次

1、Props(属性)、state(状态)用法,props是在父组件中指定,一经指定就不可修改;state是用来存放一些可变的数据,比如说从网络加载回来的数据;
2、props的使用:

<Image source={pic} style={{width: 193, height: 110}} />

其中source和style就是Image组件的属性,这个是react native已经封装好的组件,如果我们想在自定义component中使用props:
首先自定义一个组件MyCustomComponent,使用this.props.name来引用属性中name的值,这个name值就是从父组件中指定的:

class MyCustomComponent extends Component {
    render() {
        return (
            <View>
                <Text>
                    {this.props.name}
                </Text>
                <Text>
                    {this.props.age}岁
                </Text>
            </View>
        )
    }
}

export default class App extends Component {
    render() {
        return (
            <View>
                <MyCustomComponent
                    name={'zhangsan'}
                    age={18}
                />
            </View>
        )
    }
}

最后结果:


1.png

3、state的使用:通过this.setState改变状态,会重新渲染页面;

//默认是zhangsan,点击按钮,改变为lisi
//TouchableOpacity是可以响应用户触摸事件的组件
class MyCustomComponent extends Component {
    constructor(props) {
        super(props);
        this.state = {
            name: 'zhangsan'
        }
    }

    render() {
        return (
            <View>
                <Text>
                    {this.state.name}
                </Text>
                <Text>
                    {this.props.age}岁
                </Text>
                <TouchableOpacity
                    style={{
                        width: 100,
                        height: 40,
                        borderRadius: 4,
                        justifyContent: 'center',
                        backgroundColor: '#1296db',
                        alignItems: 'center'
                    }}
                    onPress={() => {
                        this.setState({
                            name: 'lisi'
                        })
                    }}
                >
                    <Text style={{color: '#ffffff'}}>改变名称</Text>
                </TouchableOpacity>
            </View>
        )
    }
}

相关文章

网友评论

      本文标题:React Native学习之props与state(一)

      本文链接:https://www.haomeiwen.com/subject/zlomkftx.html