javascript - 将 Prop 从 child 传递给 parent (没有上下文)

标签 javascript reactjs ecmascript-6

我在将状态传递给 parent 时遇到了一些问题。我需要将数据从表单容器发送到应用程序,以便我可以在提交后在天气信息中显示列表的更新状态

class App extends Component {

render() {
return (
  <div className="App">
    <div className="App-header">
      <img src={logo} className="App-logo" alt="logo" />
      <h2>Weather App</h2>
    </div>
    <p className="App-intro">
      To get started, edit <code>src/App.js</code> and save to reload.
    </p>
      <FormContainer label="Name of the city:"/>
      <WeatherInfo
          nameOfCity={this.state.nameOfCity}
          weatherDescription={this.state.weatherDescription}
          windSpeed={this.state.windSpeed}
          temperature={this.state.temperature}
          maxTemperature={this.state.maxTemperature}
          minTemperature={this.state.minTemperature}
      />
  </div>
);
}
}
export default App;

表单容器

class FormContainer extends Component {

constructor(props) {
    super(props);
    this.state = {
        cityName: '',
        nameOfCity:'',
        weatherDescription:'',
        windSpeed:'',
        temperature:'',
        maxTemperature:'',
        minTemperature:''
    };
    this.handleFormSubmit = this.handleFormSubmit.bind(this);
    this.handleCityName = this.handleCityName.bind(this);
}

handleFormSubmit(e) {
    e.preventDefault();

    const SendForm = {
        cityName: this.state.cityName
    };
    console.log(SendForm);
    fetch(`http://api.openweathermap.org/data/2.5/forecast/weather?q=${SendForm.cityName}&units=metric&APPID=********`)
        .then(res => res.json())
        .then(results => {
            this.setState({
                nameOfCity: results.city.name,
                weatherDescription: results.list[0].weather[0].description,
                windSpeed: results.list[2].wind.speed,
                temperature: results.list[0].main.temp,
                maxTemperature: results.list[0].main.temp_max,
                minTemperature: results.list[0].main.temp_min
            });
        });
}

handleCityName(value) {
    this.setState({ cityName: value });
}

render() {
    return (
        <div>
        <form onSubmit={this.handleFormSubmit}>
            <label>{this.props.label}</label>
            <SearchBar
                name="CityName"
                type="text"
                value={this.state.cityName}
                placeholder="search"
                onChange={this.handleCityName}
            />
            <button type="submit"
                    className=""
                    value='Submit'
                    placeholder="Search" />
        </form>

        </div>
    );
}
}

export {FormContainer};

搜索栏组件

const SearchBar = (props) => (
<div>
    <label>{props.label}</label>
    <input name={props.name} type={props.inputType} value={props.value} placeholder={props.placeholder} onChange={(e)=>props.onChange(e.target.value)}/>
</div>
);

export default SearchBar;

和天气信息组件

const WeatherInfo = (props) => (
<div>
    <ul>
        <li>{props.nameOfCity}</li>
        <li>{props.weatherDescription}</li>
        <li>{props.windSpeed}</li>
        <li>{props.temperature}</li>
        <li>{props.maxTemperature}</li>
        <li>{props.minTemperature}</li>
    </ul>
</div>
);

export default WeatherInfo;

最佳答案

你可以传递方法来更新 App 状态到 FormContainer 组件

class App extends Component {

constructor() {
    this.state = {
        cityName: '',
        nameOfCity:'',
        weatherDescription:'',
        windSpeed:'',
        temperature:'',
        maxTemperature:'',
        minTemperature:''
    };
}

updateInfo(results) {
   this.setState({
                nameOfCity: results.city.name,
                weatherDescription: results.list[0].weather[0].description,
                windSpeed: results.list[2].wind.speed,
                temperature: results.list[0].main.temp,
                maxTemperature: results.list[0].main.temp_max,
                minTemperature: results.list[0].main.temp_min
            });
 }

render() {
return (
  <div className="App">
    <div className="App-header">
      <img src={logo} className="App-logo" alt="logo" />
      <h2>Weather App</h2>
    </div>
    <p className="App-intro">
      To get started, edit <code>src/App.js</code> and save to reload.
    </p>
      <FormContainer label="Name of the city:" updateInfo={this.updateInfo.bind(this)}
          nameOfCity={this.state.nameOfCity}
      />
      <WeatherInfo
          nameOfCity={this.state.nameOfCity}
          weatherDescription={this.state.weatherDescription}
          windSpeed={this.state.windSpeed}
          temperature={this.state.temperature}
          maxTemperature={this.state.maxTemperature}
          minTemperature={this.state.minTemperature}
      />
  </div>
);
}
}
export default App;

并从 FormComponent 中调用它

class FormContainer extends Component {

constructor(props) {
    super(props);
    this.handleFormSubmit = this.handleFormSubmit.bind(this);
    this.handleCityName = this.handleCityName.bind(this);
}

handleFormSubmit(e) {
    e.preventDefault();

    const SendForm = {
        cityName: this.props.cityName
    };
    console.log(SendForm);
    fetch(`http://api.openweathermap.org/data/2.5/forecast/weather?q=${SendForm.cityName}&units=metric&APPID=********`)
        .then(res => res.json())
        .then(results => {
            this.props.updateInfo(results);
        });
}

handleCityName(value) {
    // Do what you want to do, like resend API request or smth
}

render() {
    return (
        <div>
        <form onSubmit={this.handleFormSubmit}>
            <label>{this.props.label}</label>
            <SearchBar
                name="CityName"
                type="text"
                value={this.props.cityName}
                placeholder="search"
                onChange={this.handleCityName}
            />
            <button type="submit"
                    className=""
                    value='Submit'
                    placeholder="Search" />
        </form>

        </div>
    );
}
}

export {FormContainer};

关于javascript - 将 Prop 从 child 传递给 parent (没有上下文),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41980278/

相关文章:

javascript - EcmaScript5 中的 WeakMap 实现?

javascript - 使用 Javascript 从浏览器截屏?

reactjs - 如何从 api 获取数据并将其作为 props 传递

reactjs - 屏幕有时会在iOS上移至右侧

reactjs - React JS - 如何在对象内添加对象

javascript - 这些额外参数如何与 map() 一起使用?

javascript - 如何比较和过滤es6中两个对象数组中不匹配的数组

javascript - 输出好友姓名而不是 ID

javascript - 如何使按钮不可点击或按下后隐藏

javascript - 路由和路由处理程序之间的函数未按预期执行