Javascript 反应-如何从另一个组件更改组件内的状态?

Javascript 反应-如何从另一个组件更改组件内的状态?,javascript,node.js,reactjs,react-redux,state,Javascript,Node.js,Reactjs,React Redux,State,这就是我想做的;我在App.js中有几个组件,包括导航栏 目前,我在App.js中有一些代码,只需点击一个按钮,它就会隐藏App.js中的几个组件,并同时显示不同的视图 我试图做的是将按钮移动到导航栏,但仍然能够在App.js中切换视图。如何在navigationbar和App.js之间共享状态 这是我的App.js代码 class App extends React.Component { constructor(props) { super(props); this.st

这就是我想做的;我在App.js中有几个组件,包括导航栏

目前,我在App.js中有一些代码,只需点击一个按钮,它就会隐藏App.js中的几个组件,并同时显示不同的视图

我试图做的是将按钮移动到导航栏,但仍然能够在App.js中切换视图。如何在navigationbar和App.js之间共享状态

这是我的App.js代码

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      searchTerm: "",
      fileType: "",
      resultStats: {},
      sidebarShowing: false,
      resultFile: {},
      showMainView: false,
      featuresVisible: true,
    };
    this.searchReturn = this.searchReturn.bind(this);
    this.fileTypeChanged = this.fileTypeChanged.bind(this);
    this.resultStatsParse = this.resultStatsParse.bind(this);
    this.fileClicked = this.fileClicked.bind(this);
    this.onHide = this.onHide.bind(this);
    this.settingsFound = this.settingsFound.bind(this);
    this.togglemainView = this.toggleMainView.bind(this);
  }

  toggleMainView = () =>
    this.setState({
      showMainView: !this.state.showMainView,
      featuresVisible: !this.state.featuresVisible,
   });

  settingsFound(style) {
    console.log("Found style");
    console.log(style);
    this.setState({ style: style });
  }

  searchReturn(searchResult) {
   console.log(searchResult);
   this.setState({ searchTerm: searchResult });
  }

  fileTypeChanged(fileType) {
   console.log(fileType);
   this.setState({ fileType });
 }

 resultStatsParse(resultStats) {
   console.log(resultStats);
   this.setState({ resultStats: resultStats });
 }

 fileClicked(file) {
   this.setState({ resultFile: file });
   this.setState({ sidebarShowing: true });
   console.log(file);
}

 onHide() {
   this.setState({ sidebarShowing: false });
}

render() {
const { showMainView } = this.state;

let showingResultsText = (
  <>
    Found {this.state.resultStats.totalResults} Results out of{" "}
    {this.state.resultStats.totalDocuments} for{" "}
    <span>{this.state.searchTerm}</span> in{" "}
    {this.state.resultStats.timeTook}ms
  </>
);
let fileText = <></>;
if (!this.state.searchTerm)
  showingResultsText = (
    <>
      Found {this.state.resultStats.totalResults} Results out of{" "}
      {this.state.resultStats.totalDocuments} in{" "}
      {this.state.resultStats.timeTook}ms
    </>
  );

if (this.state.fileType !== "") {
  fileText = (
    <>
      {" "}
      showing only <span>.{this.state.fileType}</span>
    </>
  );
}

let sidebarActive = this.state.sidebarShowing;
let style = this.state.style;

if (style == undefined) {
  return (
    <>
      <SettingsFetchComponent
        styleUpdated={this.settingsFound}
      ></SettingsFetchComponent>
      Loading your settings, please wait...{" "}
    </>
  );
}

return (
  <>
    <NavBar
      onSearchTermChanged={this.searchReturn}
      styleOptions={this.state.style}
      showMainView={this.state.showMainView}
      featuresVisible={this.state.featuresVisible}
    ></NavBar>

    <div>
      {this.state.featuresVisible ? (
        <div
          className="content"
          style={{ backgroundColor: style.backgroundColor }}
        >
          <div
            className="sidebar"
            style={{ backgroundColor: style.sidebarBackgroundColor }}
          >
            <FileTypeBar
              fileTypeChanged={this.fileTypeChanged}
              styleOptions={this.state.style}
            ></FileTypeBar>
          </div>
          <div
            className="results"
            style={{ backgroundColor: style.backgroundColor }}
          >
            <div
              className="resultsSubheader"
              style={{ color: style.secondaryTextColor }}
            >
              {showingResultsText}
              {fileText}
            </div>
            <SearchResultList
              onFileActiveChange={this.fileClicked}
              searchTerm={this.state.searchTerm}
              fileType={this.state.fileType}
              pageNumber={1}
              onResultsStats={this.resultStatsParse}
              styleOptions={this.state.style}
            ></SearchResultList>
          </div>
        </div>
      ) : null}
    </div>

    <div>
      <button onClick={this.toggleMainView}>Toggle</button>
    </div>
  </>
);
}
}
类应用程序扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
搜索词:“”,
文件类型:“”,
结果状态:{},
侧边栏显示:错误,
结果文件:{},
showMainView:false,
特征可视:正确,
};
this.searchReturn=this.searchReturn.bind(this);
this.fileTypeChanged=this.fileTypeChanged.bind(this);
this.resultStatsParse=this.resultStatsParse.bind(this);
this.fileClicked=this.fileClicked.bind(this);
this.onHide=this.onHide.bind(this);
this.settingsFound=this.settingsFound.bind(this);
this.togglemainView=this.togglemainView.bind(this);
}
toggleMainView=()=>
这是我的国家({
showMainView:!this.state.showMainView,
featuresVisible:!this.state.featuresVisible,
});
设置查找(样式){
console.log(“发现样式”);
console.log(风格);
this.setState({style:style});
}
searchReturn(searchResult){
console.log(searchResult);
this.setState({searchTerm:searchResult});
}
文件类型已更改(文件类型){
log(文件类型);
this.setState({fileType});
}
resultStatsParse(resultStats){
console.log(resultStats);
this.setState({resultStats:resultStats});
}
文件已单击(文件){
this.setState({resultFile:file});
this.setState({sidebarShowing:true});
console.log(文件);
}
onHide(){
this.setState({sidebarShowing:false});
}
render(){
const{showMainView}=this.state;
让showingResultsText=(
找到{this.state.resultStats.totalResults}个结果(共{“”}
{this.state.resultStats.totalDocuments}的{this.state.resultStats.totalDocuments}
{“}中的{this.state.searchTerm}
{this.state.resultStats.timetake}ms
);
让fileText=;
如果(!this.state.searchTerm)
showingResultsText=(
找到{this.state.resultStats.totalResults}个结果(共{“”}
{“}中的{this.state.resultStats.totalDocuments}
{this.state.resultStats.timetake}ms
);
如果(this.state.fileType!==“”){
文件文本=(
{" "}
仅显示。{this.state.fileType}
);
}
让sidebarActive=this.state.sidebarShowing;
让style=this.state.style;
如果(样式==未定义){
返回(
正在加载设置,请稍候…{“”}
);
}
返回(
{this.state.features可见吗(
{showingreultstext}
{fileText}
):null}
切换
);
}
}
这是我的导航条形码

export default class NavBar extends React.Component {
 constructor(props) {
  super(props);
 }

render() {
 let style = this.props.styleOptions;
 return (
   <nav
    class="navbar fixed-top"
    style={{
      backgroundColor: style.navBackground,
      borderColor: style.navBorderColor,
    }}
  >
    <div
      className="nav-brand-conainter"
      style={{ backgroundColor: style.navLogoBackground }}
    >
      <a class="navbar-brand" href="#">
        <img src={style.logoUrl} alt="" />
      </a>
    </div>
    <div className="navbar-contents">
      <SearchBar
        onSearchTermChanged={this.props.onSearchTermChanged}
        style={{ color: style.secondaryTextColor }}
      ></SearchBar>
    </div>
    <UserBox></UserBox>
  </nav>
);
}
}
导出默认类NavBar扩展React.Component{
建造师(道具){
超级(道具);
}
render(){
让style=this.props.styleOptions;
返回(
);
}
}

我希望能够从导航栏按钮中隐藏App.js中的组件,谢谢。

根据您的代码,您似乎已经知道如何操作了。就拿
onSearchTermChanged
为例

导航栏中执行以下操作:

    ...
    <div>
      <button onClick={this.props.onToggle}>Toggle</button>
    </div>
    ...
。。。
切换
...

如果您的导航栏需要知道状态,您可以考虑添加一个额外的处理程序:

  constructor(props) {
    ...
    this.handleToggle = this.handleToggle.bind(this);
  }

  handleToggle() {
    this.setState({ toggled: !this.state.toggled });
    this.props.onToggle();
  }

  render() {
    ...
    <div>
      <button onClick={this.handleToggle}>Toggle</button>
    </div>
    ...
  }
构造函数(道具){
...
this.handleToggle=this.handleToggle.bind(this);
}
手语{
this.setState({toggled:!this.state.toggled});
this.props.onToggle();
}
render(){
...
切换
...
}
在应用程序组件中:

    ...
    <NavBar
      onSearchTermChanged={this.searchReturn}
      onToggle={this.toggleMainView} // <----
      styleOptions={this.state.style}
      showMainView={this.state.showMainView}
      featuresVisible={this.state.featuresVisible}
    ></NavBar>
    ...
。。。

要在一个组件中共享状态,可以使用HOC或更高阶组件来实现。请按照下面的视频链接,以清楚地了解问题。我认为这将有助于解决您的问题