在 react 中,当我将信息从 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 在组件之间传递信息,反之亦然。
最佳答案
请注意,您在 App
和 App2
之间存在循环依赖。 Typescript 无法推断 App2#render
的返回类型,因为它在其返回表达式中使用了 App
,而返回表达式又使用了尚未使用的 App2
完全定义...
长话短说 - 如下声明渲染方法:
public render(): JSX.Element {
// ...
}
感谢这个 Typescript 编译器知道 render
签名而无需查看函数内容。
关于javascript - 将 Prop 从一个组件传递到另一个组件时出错 - 使用 typescript 进行 react 时反之亦然,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51380705/