我的结构如下所示:

Component 1

 - |- Component 2


 - - |- Component 4


 - - -  |- Component 5

Component 3

组件3应该根据组件5的状态显示一些数据。

因为道具是不可变的,我不能简单地在组件1中保存它的状态并转发它,对吗?是的,我读过Redux,但我不想使用它。我希望只用react就能解决这个问题。我错了吗?


当前回答

只需通过props将父组件的setState函数传递给子组件。

function ParentComp() {
  const [searchValue, setSearchValue] = useState("");
  return <SearchBox setSearchValue={setSearchValue} searchValue={searchValue} />;
}

然后在子组件中:

function SearchBox({ searchValue, setSearchValue }) {
  return (
        <input
          id="search-post"
          type="text"
          value={searchValue}
          onChange={(e) => setSearchValue(e.target.value)}
          placeholder="Search Blogs ..."
        />
    )
}

处理子组件点击的第二个例子:

// We've below function and component in parent component
const clickHandler = (val) => {
  alert(`httpRequest sent. \nValue Received: ${val}`);
};

// JSX
<HttpRequest clickHandler={clickHandler} />

这就是你如何从父组件中获取函数,然后传递一个值并通过它触发clickHandler。

function HttpRequest({ clickHandler }) {
  const [content, setContent] = useState("initialState");

  return (
    <button onClick={() => clickHandler(content)}>
      Send Request
    </button>
  );
}

export default HttpRequest;

其他回答

当您需要在子节点和父节点之间进行任何级别的通信时,最好利用上下文。在父组件中定义可以被子组件调用的上下文,例如:

在父组件中,在你的案例中,组件3,

static childContextTypes = {
    parentMethod: React.PropTypes.func.isRequired
};

getChildContext() {
    return {
        parentMethod: (parameter_from_child) => this.parentMethod(parameter_from_child)
    };
}

parentMethod(parameter_from_child){
    // Update the state with parameter_from_child
}

现在在子组件中(在你的例子中是组件5),只需告诉这个组件它想要使用它的父组件的上下文。

static contextTypes = {
    parentMethod: React.PropTypes.func.isRequired
};

render() {
    return(
        <TouchableHighlight
            onPress = {() => this.context.parentMethod(new_state_value)}
            underlayColor='gray' >

            <Text> update state in parent component </Text>

        </TouchableHighlight>
)}

您可以在这个GitHub存储库中找到Demo项目。

我们可以通过将一个函数作为props传递给子组件来设置子组件的父状态,如下所示:

class Parent extends React.Component{
    state = { term : ''}

     onInputChange = (event) => {
         this.setState({term: event.target.value});
     }

     onFormSubmit = (event) => {
         event.preventDefault();
         this.props.onFormSubmit(this.state.term);
     }

     render(){
         return (
             <Child onInputChange={this.onInputChange} onFormSubmit=
                {this.onFormSubmit} />
         )
     }
}


class Child extends React.Component{

     render(){
         return (
             <div className="search-bar ui segment">
                 <form className="ui form" onSubmit={this.props.onFormSubmit}>
                     <div class="field">
                         <label>Search Video</label>
                         <input type="text" value={this.state.term} onChange=
                             {this.props.onInputChange} />
                     </div>
                 </form>
             </div>
         )
     }
}

这样,子进程将更新父进程的状态onInputChange和onFormSubmit是父进程传递的道具。这可以从子进程中的事件侦听器调用,因此状态将在那里更新。

这是如何使用新的useState钩子。

方法-将状态改变器函数作为道具传递给子组件,并对该函数做任何你想做的事情:

import React, {useState} from 'react';

const ParentComponent = () => {
  const[state, setState]=useState('');
  
  return(
    <ChildComponent stateChanger={setState} />
  )
}


const ChildComponent = ({stateChanger, ...rest}) => {
  return(
    <button onClick={() => stateChanger('New data')}></button>
  )
}

要设置子进程中父进程的状态,可以使用回调函数。

const Child = ({handleClick}) => (
    <button on click={() => handleClick('some vale')}>change value</button>
)

const parent = () => {
    const [value, setValue] = useState(null)

    return <Child handleClick={setValue} />
}

在你的结构中,组件1和组件3似乎是兄弟。所以你有三个选择:

1-将状态放入它们的父级(不推荐4层父子级)。

2-同时使用useContext和useRducer(或useState)。

3-使用状态管理器,如redux, mobx…

<Footer 
  action={()=>this.setState({showChart: true})}
/>

<footer className="row">
    <button type="button" onClick={this.props.action}>Edit</button>
  {console.log(this.props)}
</footer>

Try this example to write inline setState, it avoids creating another function.