【React Native】基础知识

1、Props(属性)

自定义的组件也可以使用props。通过在不同的场景使用不同的属性定制,可以尽量提高自定义组件的复用范畴。只需在render函数中引用this.props,然后按需处理即可。下面是一个例子:

1.png
import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View 
} from 'react-native';

class Greeting extends Component {
  render() {
    return (
      <Text>Hello {this.props.name}</Text>
    );
  }
}

export default class reactNativeBasis extends Component {
  render() { 
    return (
      <View style={styles.container}>  
        <Greeting name='huage' />
        <Greeting name='fang' />
        <Greeting name='feng' />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  }
});

AppRegistry.registerComponent('reactNativeBasis', () => reactNativeBasis);

备注:props是在父组件中指定,而且一经指定,在被指定的组件的生命周期中则不再改变

2、state(状态)

我们使用两种数据来控制一个组件:propsstateprops是在父组件中指定,而且一经指定,在被指定的组件的生命周期中则不再改变。 对于需要改变的数据,我们需要使用state
一般来说,你需要在constructor中初始化state,然后在需要修改时调用setState方法。
假如我们需要制作一段不停闪烁的文字。文字内容本身在组件创建时就已经指定好了,所以文字内容应该是一个prop。而文字的显示或隐藏的状态(快速的显隐切换就产生了闪烁的效果)则是随着时间变化的,因此这一状态应该写到state中。

2.png
class Blink extends Component {
  constructor(props) {
    super(props)
    this.state = {showText: true};

    // 每1000毫秒对showText状态做一次取反操作
    setInterval(() => {
      this.setState(previousState => {
        return {showText: !previousState.showText}
      });
    },1000);
  }
  render() {
    let display = this.state.showText ? this.props.text: ''
    return (
      <Text>{display}</Text>
    );
  }
}

export default class reactNativeBasis extends Component {
  render() { 
    return (
      <View style={styles.container}>  
        <Blink text='I love to blink' />
        <Blink text='Yes blinking is so great' />
        <Blink text='Why did they ever take this out of HTML' />
        <Blink text='Look at me look at me look at me' />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  }
});

AppRegistry.registerComponent('reactNativeBasis', () => reactNativeBasis);

When setState is called, reactNativeBasis will re-render its Component. By calling setState within the Timer, the component will re-render every time the Timer ticks.

3、Handling Text Input(处理文本输入)

TextInput
is a basic component that allows the user to enter text. It has an onChangeText
prop that takes a function to be called every time the text changed, and an onSubmitEditing
prop that takes a function to be called when the text is submitted.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容