javascript - 如何在 React 中的功能组件之间传递数据?
问题描述
在 React 中,我们可以通过以下方式使用状态和道具在基于类的组件之间传递数据:
应用程序.js
import Name from './Name';
import React, { Component } from 'react'
export class App extends Component {
state = {
name: "Tarun"
}
render() {
return (
<Name name={this.state.name}/>
)
}
}
export default App
名称.js
import React, { Component } from 'react'
export class Name extends Component {
render() {
return (
<div>
My name is : {this.props.name}
</div>
)
}
}
export default Name
App.js
但是现在既然 React 已经引入了函数式组件,那么如果我对和都使用函数式组件,那么等效的代码是什么Name.js
?
解决方案
使用钩子你可以写这样的东西。
在App
:
import React, { useState } from 'react'
export default function App() {
// `useState` returns an array with the state
// and the method used to update the state
// You can initialise the state with a variable/object
const [name, setName] = useState('Tarun');
// No need for a render method
// Just return the JSX from the function
return <Name name={name} />;
}
在Name
:
import React from 'react'
// Props are passed down like normal function args
// Destructure `names` from the props object
export default function Name({ name }) {
return <div>My name is: {name}</div>;
}
推荐阅读
- bash - 给定参数行号和带有特殊字符的替换字符串用新行替换文件中的整行
- robotframework - 在机器人框架中如何在执行期间控制台登录
- cmd - 问题创建新进程 cmd.exe,打开然后立即关闭 VB6/Windows 10
- javascript - 递归更改对象嵌套属性名称
- javascript - 重置按钮以重置 rgb 范围滑块
- gdb - 了解 gdb 回溯
- reactjs - 如何将图像下载到“reactjs src 文件夹”
- java - 序列化和反序列化二叉树
- c# - 调用安全的 ASP.NET Core 5 Web API 会导致 HTTP 406 - Not Acceptable 错误
- python - Discord bot 命令随机停止与 python 一起工作?