React 组件间传值
一、React创建组件的方法
创建组件的方法
组件包括:函数组件和类组件
函数组件
function fn(props){
return <h1>Hello,{
props.name}</h1>;
}
类组件
//引入react模块
import React from 'react';
//声明子组件son
class R extends React.Component {
//重写方法render
render() {
return (
// 模板字串
<React.Fragment>
{
/* jsx */}
<h1>hello,{
props.name}</h1>
</React.Fragment>
);
}
}
二、props属性和state属性
1 props属性及用法
1、proprs属性是组件之间用来传递参数的,但是props的数据是不可以修改的。并且function中没有构造器,所以只有porps属性传 递数据。
2、 用法
{this.props.name}
1 state属性及用法
1、 state属性,class声明的组件中有constructor构造函数,可以声明state属性,state属性是class私有的属性,所以值是可以修改的。
2、用法
{this.state.[name]}
修改
{this.setState({ name:值 })}
二、React 传值
首先,我们的HTML代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="description" content="Web site created using create-react-app" />
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.