【问题标题】:update the state of a component from another component从另一个组件更新一个组件的状态
【发布时间】:2020-07-01 22:14:03
【问题描述】:

我想从另一个组件更新组件的图标。每当我单击播放列表音乐开始播放并且图标应该更改为暂停而不是播放但我不知道如何从另一个组件更新组件的状态。

播放列表组件 - 播放列表和音乐都在这个组件中

class PlayList extends React.Component {
    render() {
        const playMusic = () => {
            musics.forEach(e => e.pause());
            musics[this.props.arr].play();
            musics[this.props.arr].currentTime = 0;
            nowPlaying = this.props.arr;
            clickedOnMusic = 'clicked';
        };
        return (
            <div>
                <Card>
                    <CardActionArea onClick={playMusic} />
                </Card>
            </div>
        )
}



BottomAppBar 组件 - 图标和一些播放音乐的功能在这里

class BottomAppBar extends React.Component {
    state = {
        displayPlay: 'none',
        displayPause: '',
        displayVolume: '',
        displayMute: 'none'
    };
    render(){
        return(
            <IconButton onClick={handleChangePlay} style={{ color: 'white' }}>
                <PauseCircleOutlineRoundedIcon
                    style={{ fontSize: 46, display: this.state.displayPlay }}
                />
                <PlayCircleOutlineIcon
                    style={{ fontSize: 46, display: this.state.displayPause }}
                />
      )
}

非常感谢您的阅读!

【问题讨论】:

  • 你可以使用 redux 来做到这一点,也可以使用 react hooks
  • 是的,但我写了很多代码。在这里无法重构为 redux,但你是对的

标签: javascript reactjs


【解决方案1】:

将它们包装在一个容器中并在那里保持它们的状态。 例如:

<Parent>
   <PlayList/>
   <BottomAppBar />
</Parent>

【讨论】:

  • 你能解释一下吗
【解决方案2】:

您可以使用 context api,PlayerLogic 的任何升序都可以访问您使用 React.useContext 放入 context 中的任何内容,并且将在 Context 中的值更改时重新呈现。

const PlayerContext = React.createContext();
const PlayerLogic = ({ children }) => {
  const [state, setState] = React.useState({
    playing: false,
  });
  const setPlaying = React.useCallback(
    val =>
      setState(current => ({ ...current, playing: val })),
    []
  );
  const pause = React.useCallback(() => setPlaying(false), [
    setPlaying,
  ]);
  const play = React.useCallback(() => setPlaying(true), [
    setPlaying,
  ]);
  return (
    <PlayerContext.Provider
      value={{
        state,
        pause,
        play,
      }}
    >
      {children}
    </PlayerContext.Provider>
  );
};
const ComponentOne = () => {
  const {
    pause,
    play,
    state: { playing },
  } = React.useContext(PlayerContext);
  return (
    <div>
      {playing ? (
        <button onClick={pause}>pause</button>
      ) : (
        <button onClick={play}>play</button>
      )}
    </div>
  );
};
class ComponentTwo extends React.Component {
  render() {
    return this.context.state.playing
      ? 'now playing'
      : 'nothig is playing';
  }
}
ComponentTwo.contextType = PlayerContext;
const A = () => <B />;
const B = () => <C />;
const C = () => {
  const {
    state: { playing },
  } = React.useContext(PlayerContext);
  return `In component C, is playing ${JSON.stringify(
    playing
  )}`;
};
const App = () => (
  <PlayerLogic>
    <ComponentOne />
    <ComponentTwo />
    <div>
      <A />
    </div>
  </PlayerLogic>
);

ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>

【讨论】:

  • 我没有使用钩子,我想保存程序的核心
  • @TuR1NG 将 ComponentTwo 更改为一个类。 I want to save the core of program 不确定你的意思,目前上下文只有 3 个可以轻松设置的属性。
猜你喜欢
  • 2017-10-06
  • 1970-01-01
  • 2021-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-19
  • 1970-01-01
  • 2019-12-11
相关资源
最近更新 更多