【问题标题】:How to display one component's input value to another components using props in REACTJS?如何使用 REACTJS 中的 props 将一个组件的输入值显示给另一个组件?
【发布时间】:2021-04-16 09:20:06
【问题描述】:

这是一个简单的项目,我想将 firstComponent 的 输入值显示给另一个组件(secondComponent),但我无法显示另一个组件。现在,我需要建议来做这个项目,我在下面给出了代码,

App.js:

import React from 'react';
import './App.css';
import First from './components/firstComponent';
import Second from './components/secondComponent';

function App() {
return (
<div className="App">
<br/><br/>
<First />
<hr/> <hr>
<Second/>
</div>
);
}

export default App;

firstComponent.jsx:

import React from 'react';

const firstComponent = ()=> {
function handleChange(event) {
const inputValue = event.target.value;
console.log(inputValue);
}
return (
<div>
<h1><u>First Component</u> </h1>
<input type="text" style={{ width: "500px", height:"30px" }} onChange={handleChange}/>
</div>
)
}

export default firstComponent

;

secondComponent.jsx:

import React from 'react';

const secondComponent = (props) => {
return (
<div>
  <h1><u>Second Component</u> </h1>
  <h4>{this.props.inputValue}</h4>
</div>
)
}

export default secondComponent;

 

注意:我已将输出页面附在附件部分,请关注。

【问题讨论】:

  • 您需要在第一和第二组件之间建立关系。第二个组件没有收到来自第一个组件的任何道具。
  • Redux 是处理这种情况的常用方法。 First 会在 Redux 中输入一个值,Second 会从 Redux 中获取它。每当值更改时,Redux 都会为您刷新第二个组件。设置起来有点重,但我认为值得
  • @AlwaysLearning 谢谢你的意见,兄弟。
  • 毫无疑问,Redux 在这里会有所帮助,但我们在 React 本身也有一个解决方案,即上下文 API,只需将两个组件包装在上下文 api 中,FirstComponent 将是生产者,Secondcomponent 将是消费者。
  • 您也可以将输入设置为App 组件中的状态,您将 setState 方法传递给 firstComponent 并将值传递给第二个组件

标签: javascript reactjs react-props react-component


【解决方案1】:

请尝试下面给出的代码。这有望满足您的要求。

App.js


import FirstComponent from './FirstComponent'
const App = () => {
    return ( 
       <>
        <FirstComponent / >
        </>
    )
}

export default App

FirstComponent.js


import React, { useState } from "react";
import SecondComponent from "./error";

function FirstComponent() {
  const [inputData, setInputData] = useState();

  return (
    <>
      <div>
        <h1>
          <u>First Component</u>{" "}
        </h1>
        <input
          type="text"
          style={{ width: "500px", height: "30px" }}
          onChange={(e) => setInputData(e.target.value)}
        />
        <br />
        <SecondComponent inputValue={inputData} />
      </div>
    </>
  );
}
export default FirstComponent;


SecondComponent.js


import React from 'react';

const secondComponent = (props) => {
return (
<div>
  <h1><u>Second Component</u> </h1>
  <h4>{props.inputValue}</h4>
</div>
)
}

export default secondComponent;

【讨论】:

  • 非常感谢。你是对的,它正在工作。
猜你喜欢
  • 1970-01-01
  • 2016-01-14
  • 1970-01-01
  • 1970-01-01
  • 2019-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多