简体   繁体   English

从子级更改父级组件道具/状态

[英]Change parent component props/state from child

I'm currently learning REACT to create a web app. 我目前正在学习REACT,以创建网络应用。 In this app, I have a list of selectedCharacters in the parent's state and in each child component I have an input for the player name. 在这个应用程序中,我有一个处于父级状态的selectedCharacters列表,在每个子级组件中,我都有一个播放器名称输入。 I'm struggling to update the player name in the parent's state. 我正在努力更新处于家长状态的玩家名称。

class Game extends React.Component {
  state = {
    selectedCharacters: [{"name":"Loup Garou","imgName":"base_loup.png","uniqueKey":"loup","playerName":""},{"uniqueKey":"voyante","imgName":"base_voyante.png","name":"Voyante","maxInGame":1,"left":1}]
  };
  changePlayerName = (char, newName) => {
    char.playerName = newName;
  };
  render() {
    const { selectedCharacters } = this.state;
    return(<CharactersSelection selectedCharacters={selectedCharacters} />);  
  }
}

const CharactersSelection = props => {
  return (
    <div className="row col-12 char-list">      
      <div className="col-md-9 col-xl-10 char-selected pad-r-10 pad-l-10">
        <div className="row char-selected-content">
          {props.selectedCharacters.map((char, i) => (
            <CharacterCardSelected key={i} imgName={char.imgName} name={char.name} playerName={char.playerName}/>
          ))}
        </div>
      </div>
    </div>
  );
};

const CharacterCardSelected = props => {
  return (
    <div className="d-flex char-card-selected" id={props.id}>
      <img alt={props.imgName} className="char-img-sm" src=require("../../public/images/" + props.imgName)}/>
      <div className="char-card-selected-txt">
        <div>
          <input
            type="text"
            className="form-control player-name"
            placeholder="Nom joueur..."
            value={props.playerName}
            onChange={e => {console.log(e)}}
          />
        </div>
      </div>
    </div>
  );
};

Help will be appreciated. 帮助将不胜感激。

What you will do is pass the changePlayerName function as a prop to CharactersSelection and from there pass it further down to CharacterCardSelected component. 您要做的是将changePlayerName函数作为对CharactersSelection的支持,然后从那里进一步传递给CharacterCardSelected组件。 Now onChange of CharacterCardSelected call the method this.props.changePlayerName(name); 现在onCharacterCardSelected的onChange调用方法this.props.changePlayerName(name);

class Game extends React.Component {
  state = {
    selectedCharacters: [{"name":"Loup Garou","imgName":"base_loup.png","uniqueKey":"loup","playerName":""},{"uniqueKey":"voyante","imgName":"base_voyante.png","name":"Voyante","maxInGame":1,"left":1}]
  };
  changePlayerName = (char, newName) => {
    char.playerName = newName;
  };
  render() {
    const { selectedCharacters } = this.state;
    return(<CharactersSelection selectedCharacters={selectedCharacters} onChange={this.changePlayerName} />);  
  }
}

const CharactersSelection = props => {
  return (
    <div className="row col-12 char-list">      
      <div className="col-md-9 col-xl-10 char-selected pad-r-10 pad-l-10">
        <div className="row char-selected-content">
          {props.selectedCharacters.map((char, i) => (
            <CharacterCardSelected key={i} imgName={char.imgName} name={char.name} playerName={char.playerName} onChange={(newName) => {props.onChange(char,newName)}}/>
          ))}
        </div>
      </div>
    </div>
  );
};

const CharacterCardSelected = props => {
  return (
    <div className="d-flex char-card-selected" id={props.id}>
      <img alt={props.imgName} className="char-img-sm" src=require("../../public/images/" + props.imgName)}/>
      <div className="char-card-selected-txt">
        <div>
          <input
            type="text"
            className="form-control player-name"
            placeholder="Nom joueur..."
            value={props.playerName}
            onChange={e => {
              console.log(e);
              props.onChange(e.target.value)
            }}
          />
        </div>
      </div>
    </div>
  );
}; 

Expanding on Michael's answer: 扩展迈克尔的答案:

class Parent extends React.Component {
  state = { someValue: "" }

  onChangeValue = (event) => {
    this.setState({ someValue: event.target.value })
  }

  render () {
    const { someValue } = this.state
    return (
      <Child onChangeValue={this.onChangeValue} value{someValue}/>
    )
  }
}

class Child extends React.Component {
  render() {
    return (
      <input 
        onChange={this.props.onChangeValue} 
        value={this.props.value}
      />
    )
  }
}

This is a common pattern in React called Lifting State Up 这是React中的一种常见模式,称为“ 提升状态”

Try creating a function in the parent component and then passing it to the Child component. 尝试在父组件中创建一个函数,然后将其传递给Child组件。 Assign the name to a state variable in the parent and pass that to the child component. 将名称分配给父级中的状态变量,然后将其传递给子级组件。

Pass the changePlayerName function to the lowest child. 将changePlayerName函数传递给最低的子级。 From there you need to trigger the setState of the parent component, in order to change the player's name. 从那里开始,您需要触发父组件的setState,以更改播放器的名称。

class Game extends React.Component {
        constructor(props) {
          super(props);
          this.state = {
            selectedCharacters: [{
              "name": "LoupGarou",
              "imgName": "base_loup.png",
              "uniqueKey": "loup",
              "playerName": ""
            }, {
              "uniqueKey": "voyante",
              "imgName": "base_voyante.png",
              "name": "Voyante",
              "maxInGame": 1,
              "left": 1
            }]
          }
        }
        changePlayerName = (index, newName) => {
          this.setState({
            selectedCharacters[index].playerName: newName
          });
        };
        render() {
          const {
            selectedCharacters
          } = this.state;
          return ( < CharactersSelection selectedCharacters = {
              selectedCharacters
            }
            changePlayerName = {
              this.changePlayerName
            }
            />);
          }
        }
        const CharactersSelection = props => {
            return ( < div className = "row col-12 char-list" > < div className =
                "col-md-9 col-xl-10 char-selected pad-r-10 pad-l-10" > < div className =
                "row char-selected-content" > {
                  props.selectedCharacters.map((char, index) => ( <
                      CharacterCardSelected key = {
                        index
                      }
                      imgName = {
                        char.imgName
                      }
                      changePlayerName = {
                        props.changePlayerName
                      }
                      name = {
                        char.name
                      }
                      playerName = {
                        char.playerName
                      }
                      />))
                    } < /div> < /div > < /div>);
                  };
                  const CharacterCardSelected = props => {
                    return ( < div className = "d-flex char-card-selected"
                      id = {
                        props.id
                      } > < img alt = {
                        props.imgName
                      }
                      className = "char-img-sm"
                      src = require("../../public/images/" + props.imgName)
                    }
                    /> < div className = "char-card-selected-txt" > < div > < input
                    type = "text"
                    className = "form-control player-name"
                    placeholder = "Nom joueur..."
                    value = {
                      props.playerName
                    }
                    onChange = {
                      (e) => props.changePlayerName(props.key, e.target.value)
                    }
                    /> < /div > < /div> < /div > );
                };

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从父 state 更改更新子组件道具值 - Update child component props values from parent state change 子项道具不反映父项的状态变化 - Child component props not reflecting state change from parent 我们可以将 setState 作为 props 从一个组件传递到另一个组件,并在 React 中从子组件更改父状态吗? - Can we pass setState as props from one component to other and change parent state from child component in React? 使用状态或道具从父组件更改子组件中输入元素的样式 - Change styling for input element in child component from parent component using state or props 从子组件更改父组件状态 - Change parent component state from child component 无法将道具从父级传递给子级并将其保存在子组件的 state 中 - Unable to pass props from parent to child and save it in state of child component 当父组件的状态发生变化时向子组件发送道具,子组件的状态总是落后于一 - Sending props to Child Component when there's a change in state of parent Component, the state of child component is always one behind 子组件无法识别父组件的道具更改 - Child component not recognizing props change from parent component 我们可以在 React 中将 props 从 Parent 传递给 Child 组件,并将 props 设置为子组件的 state 吗? - Can we pass props from Parent to Child component in React, and set the props as state of child component? Reactjs:如何从父级修改动态子组件状态或道具? - Reactjs: how to modify dynamic child component state or props from parent?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM