Home > Article > Web Front-end > Detailed explanation of props usage in React-Native
This article mainly introduces the detailed use of props in React-Native. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor and take a look.
Props are properties, which exist to describe the characteristics of a component. It is passed from the parent component to the child component.
Use props
Pass through the previous page
Create a new PropsTest.js file
exprot default class PropsTestextendesComponent{ render(){ return <Text>{this.props.name}</Text> } }
Use the PropsTest component in the previous page
import PropsTest from './PropsTest' <PropsTest name = 'XiaoMing' />
Note: The above codes are all code snippets.
Default attributes and their functions
Since the props attributes are all passed on the previous page, they cannot be modified. But we can define some default values for props in the PropsTest file.
exprot default class PropsTestextends Component{ static defaultProps={ name: 'XiaoHong' } render(){ return <Text>{this.props.name}</Text> } }
Note that defaultProps needs to be statically modified using the static keyword. In this way, if no value is passed on the previous page, the default attribute will be displayed.
Constrain and check props
exprot default class PropsTestextends Component{ static defaultProps={ name: 'XiaoHong' } static propTypes={ name: PropTypes.string, age: PropTypes.number, sex: PropTypes.string.isRequired } render(){ return <Text>{this.props.name}</Text> } }
You can use propTypes to determine the type of properties in props. It also needs to be modified using the static keyword.
isRequired can specify required items
Note:
The propTypes attribute is in the react package and needs to be imported before it can be used.
props extension operator
The latest syntax of ES6
If our component requires many properties, as follows:
params = {name: 'XiaoZhang', age: 18, sex: '男'} // 如果需要传递给下一个页面需要: <PropsTest name = {params.name} sex = {params.sex} age = {params.age} /> // 等等,这样如果属性特别多,代码将会变得难以维护。
You can use the latest stretch operator feature in ES6
<PropsTest {...params} />
Very concise
props destructuring assignment
The latest syntax of ES6
If you want to get some of the objects passed through the extension operator and use them in another component, you can use destructuring assignment
var {name, age} = params; // 其他地方就可以直接引用name和age了 {name}或{age} // 这么做的好处,同样是不需要使用如下的传统方式 {params.name}或{params.age}
The above is the detailed content of Detailed explanation of props usage in React-Native. For more information, please follow other related articles on the PHP Chinese website!