函数方法传递props
//2.接收数据
const Props = (props) => {
return(
<div>
<h1>name:{props.name}</h1>
<h1>age:{props.age}</h1>
</div>
)
}
//1.传递数据
const container = createRoot(document.getElementById('root'))
container.render(<Props name='ZhangSan' age='19'/>)
- 通过组件标签添加的属性进行传递数据
- 函数中通过props参数进行获取
效果
类组件方法传递props
//二、类组件方法传递
class Props extends React.Component{
render(){
return(
<div>
<h1>name:{this.props.name}</h1>
<h1>age:{this.props.age}</h1>
</div>
)
}
}
//1.传递数据
const container = createRoot(document.getElementById('root'))
container.render(<Props name='Lisi' age='21'/>)
效果
- 通过组件标签添加的属性进行传递数据
- 组件中通过
this.props.name
进行接收
传输类型
传输字符串类型
container.render(<Props name='LiSi' age='21'/>)
传输其他类型(例:数字)
container.render(<Props name='LiSi' age={21} />)
传输方法
container.render(
<Props
name='LiSi'
age={21}
fn={()=>console.log('funciton')}
/>
)
传输Jsx
container.render(
<Props
name='LiSi'
age={21}
fn={()=>console.log('funciton')}
tag={<p>P标签</p>}
/>
)
只读
props是只读属性,不能对值进行修改
强行修改会报:Uncaught TypeError: “name” is read-only
构造函数使用
使用类组件时,如果写了构造函数,应该将props传递给super(),否则,无法在构造函数中获取到props,其他的地方是可以拿到的
constructor(){
super()
console.log(this.props);
}
这样子的话是无法拿到props的,但是也不会影响其他组件的使用
正确的使用方法应该是:
constructor(props){
super(props)
console.log(this.props);
}
这下就可以拿到props的数据了
源码
以下是全部的代码分享:
import React from 'react';
import {createRoot} from 'react-dom/client'
// import ReactDOM from 'react-dom/client';
import './index.css';
//二、类组件方法传递
class Props extends React.Component{
// undefined
// constructor(){
// super()
// console.log(this.props);
// }
// 正确使用(推荐)
constructor(props){
super(props)
console.log(this.props);
}
render(){
console.log(this.props);
this.props.fn()
//修改props的值
// this.props.name = 'WangWu'
return(
<div>
<h1>name:{this.props.name}</h1>
<h1>age:{this.props.age}</h1>
{this.props.tag}
</div>
)
}
}
const container = createRoot(document.getElementById('root'))
// 传递字符串
container.render(<Props name='LiSi' age='21'/>)
// 传输其他类型(例:数字)
container.render(<Props name='LiSi' age={21} />)
// 传输方法函数
container.render(
<Props
name='LiSi'
age={21}
fn={()=>console.log('funciton')}
/>
)
// 传输Jsx
container.render(
<Props
name='LiSi'
age={21}
fn={()=>console.log('funciton')}
tag={<p>P标签</p>}
/>
)
//一、函数方法传递
//2.接收数据
// const Props = (props) => {
// return(
// <div>
// <h1>name:{props.name}</h1>
// <h1>age:{props.age}</h1>
// </div>
// )
// }
// //1.传递数据
// const container = createRoot(document.getElementById('root'))
// container.render(<Props name='ZhangSan' age='19'/>)