首页 > 解决方案 > 将道具从一个组件传递到另一个组件时出现错误,反之亦然,使用打字稿做出反应

问题描述

在反应中,当我将信息从 App 组件传递到 App2 组件时

<App2 value = {this.state.name}/>

它运行良好,但是当我尝试将信息从 App2 组件传递到 App1 组件时

<App1 value = {this.state.name2}/>

在 App2 组件的渲染函数中,它给出了一个错误:-

[ts] 'render' implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions.

App1 组件的代码是:-

import * as React from "react";
 import App2 from './App2';

interface IState{
    name   : string,
    age    : 5;
}

interface Iprops{
    value ? : any
}
class App extends React.Component<Iprops,IState>{
    constructor(props:any)
    {
        super(props);
        this.state = {
            age  : 5,
            name : ""   
        }
        this.change = this.change.bind(this);
    }   

    public change(event : any){
        // alert("you have submitted the form");
        this.setState({
            name : event.target.value
        });
    }
    public render()
    {
        return(
            <div>
               <input type="text" value = {this.state.name} onChange = {this.change}/>
               <App2 value = {this.state.name}/>
            </div>
        )
    }
}

export default App;

App2 组件代码是:-

import * as React from "react";
import App from './App'
interface Iprops{
    value ? : any;
}
interface Istate{
    name2 : string
}
class App2 extends React.Component<Iprops,Istate>{
    constructor(props:any)
    {
        super(props);
        this.state = {
            name2 : " "
        }

    }

    public change(event : any){
        this.setState({name2 : event.target.value})
    }

    public render() {
      return (
        <div>
          <h4>
              <input type="text" value = {this.props.value} onChange = {this.change}/>
              Hello, I am in App3 component.
              <App value = {this.state.name2}/>
          </h4>
        </div>
      )
    }
}

export default App2;

是否有任何其他方法可以在使用 typescript 的组件之间传递信息,反之亦然。

标签: javascriptreactjstypescript

解决方案


请注意,您在App和之间具有循环依赖关系App2。Typescript 无法推断返回类型,App2#render因为它App在其返回表达式中使用,而返回表达式又使用App2尚未完全定义的...

长话短说 - 声明您的渲染方法如下:

public render(): JSX.Element {
    // ...
}

感谢这个 Typescript 编译器render无需查看函数内容即可知道签名。


推荐阅读