React.js passing one components variables to another component and vice-versa

题意:“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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

营赢盈英

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值