React的props与state(上)

React的props与state(上)

props 的资料结构就是一个物件JavaScript Object,就像是var props={name:'jacky',age:29}由父元件呼叫子元件时赋与子元件数值,在子元件中props不可以改变。
取用参数时用this.props.变数名称,即可取用。

index.js

import React from 'react';import ReactDOM from 'react-dom';import ButtonTest from './buttonTest';ReactDOM.render(  <div>    <ButtonTest name="Andy" age="21" />  </div>  ,document.getElementById('root'));

子元件ButtonTest

import React from "react";class ButtonTest extends React.Component {      constructor(props){        super(props);console.log('message',this.props.name);}            render() {          return <button onClick={this.handleEdit}>编辑</button>      }}export default ButtonTest;

在index.js中会读取ButtonTest元件,并传入二个参数name及age到ButtonTest元件。

<ButtonTest name="Andy" age="21" />

有传递参数到子元件的话,就一定要有constructor(props){}来接受,不论你传几个参数过来,只要一个props来接受就行了。
要取用的话就用this.props.name来取用就行了。


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章