React Native学习之props与state(一)

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>
        )
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,923评论 18 139
  • 以下内容是我在学习和研究React时,对React的特性、重点和注意事项的提取、精练和总结,可以做为React特性...
    科研者阅读 8,291评论 2 21
  • Learn from React 官方文档 一、Rendering Elements 1. Rendering a...
    恰皮阅读 2,687评论 2 3
  • 爱生命,谨防溺水”。水是生命之源,它有温柔的一面,滋养着人类和万物;但它也有刚烈的一面,有时竟吞噬了人的生命。随着...
    古韵斋阅读 630评论 0 1
  • 我又用生命在熬夜了,深邃的夜,安静的能听见自己的呼吸声,一个人的时候,我总是在想念,想念那些欢愉的日子,回忆那些美...
    酷那么塔塔阅读 330评论 0 0