react props
React JS properties or props give more functionality to a react component.
React JS属性或道具为react组件提供更多功能。
Like most developers always say, React JS props are like HTML attributes and can also be seen as JavaScript function parameters.
就像大多数开发人员经常说的那样, React JS道具就像HTML属性一样,也可以看作JavaScript函数参数。
Props can be added to a component the same way an attribute is added to an HTML element.
可以将属性添加到组件的方式与将属性添加到HTML元素的方式相同。
The component then receives the prop as an object. Therefore, accessing the props will similar to accessing items of a JavaScript object.
然后,组件将prop作为对象接收。 因此,访问道具将类似于访问JavaScript对象的项目。
Syntax:
句法:
<App type="android" />
Where, "App" is the name of the component.
其中, “ App”是组件的名称。
Example:
例:
Quickly open the index.js file your React JS application and adjust the ReactDOM.render() line.
快速打开React JS应用程序的index.js文件,并调整ReactDOM.render()行。
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
import './index.css'
ReactDOM.render(< App kind= "android" />, document.getElementById('root'))
Let's create a file now for App component called App.js.
现在为App组件创建一个名为App.js的文件。
From our App.js file, we are going to print out the property or props of the component using the same syntax to access elements of a JavaScript object.
从App.js文件中,我们将使用相同的语法来打印组件的属性或道具,以访问JavaScript对象的元素。
import React from "react"
class App extends React.Component {
render (){
return (
<h1> This app is {this.props.kind} </h1>
)
}
}
export default App
Output
输出量
![React Js Properties](https://i-blog.csdnimg.cn/blog_migrate/df3c64053c6a33e5dc7e378c26807b1b.png)
From the example above, we added property called "kind" to the App component. The property is then accessed from the props object using the syntax this.props.kind.
在上面的示例中,我们向App组件添加了名为“ kind”的 属性 。 然后,使用语法this.props.kind从props对象访问该属性。
Props are read-only, meaning you can’t change it in a different line of code.
道具是只读的,这意味着您不能在不同的代码行中对其进行更改。
From ES6, the constructor function is used to create props in React JS components using the following syntax,
从ES6开始, 构造函数用于使用以下语法在React JS组件中创建道具 ,
class Car extends React.Component {
constructor(props) {
super(props)
}
}
render() {
return (
<div>
....
</div>
)
}
Thanks for coding with me! See you @ the next article. Feel free to drop a comment or question.
感谢您与我编码! 下次见。 随意发表评论或问题。
翻译自: https://www.includehelp.com/react-js/introduction-to-react-js-properties-props.aspx
react props