【问题标题】:Error Coming when passing props from one component to another and vice - versa in react using typescript将道具从一个组件传递到另一个组件时出现错误,反之亦然,使用打字稿做出反应
【发布时间】:2018-07-17 11:52:39
【问题描述】:

在反应中,当我将信息从 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 的组件之间传递信息,反之亦然。

【问题讨论】:

  • 那么渲染是什么样子的?..
  • 在没有看到组件代码的情况下无法回答,但是错误似乎是不言自明的

标签: javascript reactjs typescript


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 2022-01-17
    • 1970-01-01
    • 2018-07-04
    • 1970-01-01
    • 2019-11-06
    • 1970-01-01
    • 2020-11-23
    • 1970-01-01
    • 2015-09-28
    相关资源
    最近更新 更多