javascript - 将道具从一个组件传递到另一个组件时出现错误,反之亦然,使用打字稿做出反应
问题描述
在反应中,当我将信息从 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
无需查看函数内容即可知道签名。
推荐阅读
- gnuplot - Gnuplot 和“悬挂”栏
- r - 如何在 R 中用 NA 替换 0 或缺失值
- javascript - 使用 Vanilla JS 向表格动态添加内容
- swift - 将自定义 UIView 添加到 SCNNode 中未正确显示
- javascript - jquery 在依赖 jquery 的脚本之前加载,但后者仍然说“$ 未定义”
- azure - 微软翻译 API 身份验证失败
- c++ - boost asio async_receive_from() 当帧连续发送时丢失 udp 帧数据检索
- python - 如何使用海龟在 Python 中一次绘制全图?
- python - 使用 Python 请求会话发出多个请求时权限被拒绝
- http - 我可以使用 netlify 的 CDN 来阻止 lambda 一天多次执行吗?