在反应中,当我将信息从App组件传递给App2组件时
<App2 value = {this.state.name}/>
它工作正常,但是当我尝试将信息从App2组件作为
从App2组件传递到App1组件时<App1 value = {this.state.name2}/>
在App2组件的render函数中,它给出一个错误:-
[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;
是否还有其他方法可以使用打字稿在组件之间传递信息,反之亦然。
答案 0 :(得分:2)
请注意,您在App
和App2
之间具有循环依赖关系。 Typescript无法推断App2#render
的返回类型,因为它在返回表达式中使用了App
,而返回表达式又使用了尚未完全定义的App2
...
长话短说-声明您的渲染方法,如下所示:
public render(): JSX.Element {
// ...
}
由于此Typescript编译器无需查看函数内容即可知道render
签名。