【问题标题】:React Ts, Access Parents state from ChildReact Ts,从子级访问父级状态
【发布时间】:2020-04-02 18:05:40
【问题描述】:

所以我一直在尝试从子组件访问父状态,但是我不断收到错误消息,或者它不能一起工作。 我在网上找到了多种解决方案,但是它们都不适用于 React with Typescript。

所以这是我正在尝试做的简化代码示例。

export default class parent extends React.Component {

state= {
exist: true
}

render() {
    return (

    <div>
        <child>
    <div>
    )
}


export default class child extends React.Component {


componentDidMount = () => {
    document.getElementById("theText").value = "It does exist!"
}

render() {
    return (

    <div>
         <h1 id="theText">It Doesn't exist</h1>
    <div>
    )
}

PS// 这不是我正在处理的代码!我只是快速写了它,以便更容易看到我想要做什么!

【问题讨论】:

    标签: react-tsx


    【解决方案1】:

    您可以使用称为道具的东西将状态从您的父母传递给孩子。这些道具可以是变量,也可以是函数。当然,因为它是打字稿,所以你需要定义它。 props 的类型可以通过接口来定义:

    interface ChildProps {
        Exists: boolean;
    
        // You can skip this one if you don't want to alter the state
        // in the parent from the child component.
        SetExists: (value: boolean) => void;
    }
    

    接口在React.Component&lt;ChildProps&gt;中用作泛型参数

    export default class child extends React.Component<ChildProps> {
        componentDidMount = () => {
            document.getElementById("theText").value = "It does exist!"
        }
    
        render() {
            // Depending on the state of the parent, something can be rendered here.
            if(this.props.Exists)
                return <h1>Does exists! :)</h1>;
            else
                return <h1>Doesn't exist :(</h1>;
        }
    }
    

    您还需要稍微更改父组件。看起来像这样:

    export default class parent extends React.Component {
        state = {
            exist: true
        }
    
        render() {
            return (
                <div>
                    <child
    
                        // Here, the state is passed to a child component as if it
                        // were an argument of a function.
                        Exists={this.state.Exists}
                        SetExists={(x) => this.setState({ Exists: x })}
                    >
                <div>
            )
    }
    

    我希望这会有所帮助并解决您的问题。如果没有,请告诉我,以便我们继续寻找解决方案。 :)

    【讨论】:

      猜你喜欢
      • 2017-06-09
      • 1970-01-01
      • 2021-11-05
      • 1970-01-01
      • 1970-01-01
      • 2020-09-09
      • 1970-01-01
      • 1970-01-01
      • 2020-06-26
      相关资源
      最近更新 更多