你好,我是新的反应,很难将值传递到另一个组件。所以,我想要做的基本上是接受一个来自组件searchBar.js
的输入,并试图将这个值传递给另一个名为PriceModel.js
的组件。一旦PriceModel.js
接收到它将该值传递给另一个名为StockData.js
的组件的值,就会对数据进行计算,并将其传递回PriceModel.js
文件,以便以表格式打印。
searchBar.js
class SearchBar extends Component{
constructor(props){
super(props);
this.state = {
inputTicker:''
}
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit (event) {
event.preventDefault();
// this.props.handleData(this.state)
// const data = this.props.handelData(this.state);
// console.log("Current value?", data);
console.log("Current value?", this.state.inputTicker);
}
handleChange(event) {
// event.preventDefault();
console.log("Taking in value:",event.target.value);
this.setState({
inputTicker: event.target.value
});
this.props.handleSubmit(this.state);
}
render() {
return(
<>
<form onSubmit={this.handleSubmit} >
{/* <form handleSubmit={this.handleFormSubmit.bind(this)} > */}
<div className="search-container">
<span className="search-icon-btn" >
<button className="search-icon-btn"
value="Submit"
type="submit"
>
<i className="fa fa-search" ></i>
</button>
</span>
<div className="search-input">
<input
type="search"
className="search-bar"
placeholder="Search ticker symbol..."
value={this.state.inputValue}
onChange= {this.handleChange}
/>
</div>
</div>
</form>
</>
)
}
}
export default SearchBar;
PriceModel.js
import React, { Component} from 'react';
import StockData from './stockData'
import './PriceModel.css';
import SearchBar from '../navigation-Bar/searchBar';
class PriceModel extends Component{
constructor(props){
super(props);
this.state = {
ticker:{}
}
}
componentDidMount() {
// console.log("passed the value:",this.props.inputTicker);
// console.log("passed the value-1:",this.state.ticker);
}
render(){
return(
<div className="PriceModel" >
<table className="table mt-5">
<thead>
<tr>
<th>Ticker</th>
<th>Company</th>
<th>Price</th>
<th>PE Ratio</th>
</tr>
</thead>
<tbody>
{/* <SearchBar handleSubmit={this.props.handleSubmit}/> */}
<StockData ticker = {this.props.inputTicker}/>
</tbody>
</table>
</div>
);
}
}
export default PriceModel;
在这个文件中,StockData.js
只接受值并调用api来获取要评估的适当信息。一旦计算了信息,它就会传回PriceModel.js
,以表格格式打印出来。
发布于 2022-01-23 07:21:24
在您的PriceModel
组件中:
<SearchBar handleSubmit={(input)=> this.setState({ticker: input})}/>
发布于 2022-01-23 07:34:04
基本上,您需要做的是将状态提升到父级,然后在必须更改状态时传递一个函数来执行,在您的情况下,当我们在searchBar组件中更改输入时。因此,您需要一个处理更改的函数的状态,然后在父搜索栏中,然后在必须进行更改或进行类似于priceModel中的任何计算的地方,传递处理更改的函数,在需要在StockData.js中打印结果的地方,您只需将状态作为支柱传递。
您可以在react:https://reactjs.org/docs/lifting-state-up.html中阅读更多内容。
希望你明白我的意思,如果没有,告诉我,我会尽量说得更清楚。
https://stackoverflow.com/questions/70823363
复制