题意:“React.js:在组件之间传递变量(双向传递)”
问题背景:
I've just started to learn react. If I have a component with two variables, what is the easiest way to access these in another component? Use props, useState, useContext? How would you do to use the two variables inside ComponentTwo.
“我刚开始学习 React。如果我有一个包含两个变量的组件,最简单的方法是在另一个组件中访问这些变量是什么?使用 `props`、`useState`、`useContext`?你会如何在 `ComponentTwo` 中使用这两个变量?”
import React from 'react';
ComponentOne = () => {
varOne = Mike;
varTwo = Tyson;
Return(
<div>
</div>
)}
export default ComponentOne
import React from 'react';
import ComponentOne from '../OtherFolder/';
ComponentTwo = () => {
Return(
<div>
<p>{varOne}, {varTwo}</p>
</div>
)}
export default ComponentTwo```
问题解决:
It depends on your app's style. If it is a simple app where component two needs to access component one's variables props would be easy to use. However, as apps scale, you need to consider situations where component two needs to access a global state. Then, things change. Suppose your ComponentOne is the parent that contains & controls the state and ComponentTwo is the child and will only use the state passed from the parent.
“这取决于你的应用程序风格。如果是一个简单的应用,`ComponentTwo` 只需要访问 `ComponentOne` 的变量,那么使用 `props` 会很方便。然而,随着应用规模的扩大,你需要考虑 `ComponentTwo` 需要访问全局状态的情况。那时,情况会发生变化。假设 `ComponentOne` 是父组件,它包含并控制状态,而 `ComponentTwo` 是子组件,只会使用从父组件传递的状态。”
Component1.js
import React from 'react';
import ComponentTwo from "./yourcomponent2directory.js"
const ComponentOne = () => {
varOne = Mike;
varTwo = Tyson;
return
(
<div>
<ComponentTwo varOne={varOne} varTwo={varTwo}/>
</div>
)}
export default ComponentOne
ComponentTwo.js
import React from 'react';
import ComponentOne from '../OtherFolder/';
const ComponentTwo = (props) => {
return(
<div>
<p>{props.varOne}, {props.varTwo}</p>
</div>
)}
export default ComponentTwo
or you can destructure props like...
“或者你可以像这样解构 `props`...”
const ComponentTwo = ({varOne,varTwo}) => {
return(
<div>
<p>{varOne}, {varTwo}</p>
</div>
)}
export default ComponentTwo