ReactJS - 如何根据另一个组件更改组件的状态

时间:2018-06-19 02:31:15

标签: javascript reactjs

我试图在不同组件的状态发生变化时更新组件的状态。

以下是包含表单的主要组件:

class IpsumForm extends React.Component {
  state = {
    character: 'All',
    paragraphs: 1,
    ipsumDisplayed: false
  };

  handleInputChange = (e) => {
    const target = e.target;
    this.setState({ paragraphs: target.value });
  };

  handleSelectChange = (e) => {
    const target = e.target;
    this.setState({ character: target.value });
  };

  handleReset = (e) => {
    this.setState({
      character: 'All',
      paragraphs: 1,
      ipsumDisplayed: false
    });
  };

  handleSubmit = (e) => {
    e.preventDefault();
    this.setState({
      ipsumDisplayed: true
    });
  };

  render() {
    return (
      <div>
        <form onSubmit={this.handleSubmit}>
          <p>Select Your Character:</p>
          <select
            value={this.state.character}
            onChange={this.handleSelectChange}
            name="characterPick"
          >
            <option value="All">All</option>
            <option value="Michael">Michael</option>
            <option value="Dwight">Dwight</option>
            <option value="Jim">Jim</option>
            <option value="Andy">Andy</option>
            <option value="Creed">Creed</option>
          </select>
          <div className="length">
            <p>How Many Paragraphs?</p>
            <input
              onChange={this.handleInputChange}
              name="paragraphLength"
              type="text"
            />
          </div>
          <hr />
          <input
            id="submit"
            type="submit"
            value="Bibity Boppity Give Me The Zoppity"
          />
          <button onClick={this.handleReset}>Reset</button>
        </form>
        <br />
        <IpsumText
          person={this.state.character}
          length={this.state.paragraphs}
          displayed={this.state.ipsumDisplayed}
        />
      </div>
    );
  }
}

export default IpsumForm;

以下是我想在文本框中返回ipsum的组件:

class IpsumText extends React.Component {
  state = {
    value: ''
  };

  handleValueChange = (e) => {
    console.log(data.quote1);
    this.setState({
      value: data.quote1
    });
  };

  render() {
    let character = this.props.person;
    let paragraphs = this.props.length;
    let displayed = this.props.displayed;

    return (
      <div className="returned-ipsum">
        <textarea value={this.state.value} onChange={this.handleValueChange} />
      </div>
    );
  }
}

export default IpsumText;

我现在的代码不起作用,因为IpsumForm的状态更改不会导致textarea onChange处理程序在IpsumText中运行

我想知道除了使用生命周期方法之外是否还有其他方法可以做到这一点,因为看起来我只是在思考它?

1 个答案:

答案 0 :(得分:1)

这是一种非常简单的观察方式:

&#13;
&#13;
class App extends React.Component {
	state = {
		firstState: 1,
	}
	handleStateUpdate = () => {
		this.setState(prev => ({
			firstState: prev.firstState + 1
		}))
	}
	render() {
		console.log(this.state.firstState)
		return (
			<Foo handleStateUpdate={this.handleStateUpdate} />
		)
	}
}

class Foo extends React.Component {
	state = {
		otherState: 1,
	}
	handleLocalStateUpdate = () => {
		this.props.handleStateUpdate()
		this.setState(prev => ({
			otherState: prev.otherState + 1
		}))
	}
	render() {
		return <button onClick={() => this.handleLocalStateUpdate()}>Click here!</button>
	}
}

ReactDOM.render(<App />, document.getElementById('app'))
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='app'></div>
&#13;
&#13;
&#13;

这样做是将一个函数从更新父状态的父函数传递到子组件。一旦定义了更新子组件状态的函数,就可以调用传递函数来更新父状态。

希望这样做的原则有助于解决您所面临的问题。

这里是代码的链接,以防你想弄乱它:

CodePen