我正在尝试使用 React 和 Typescript 创建一个简单的选项卡应用程序。我有一个名为 Tabs 的容器组件,它处理状态并将其传递给我的内容组件。我还创建了一个 .函数名为“handleName”,我将其传递给名为 Sidebar 的功能组件。当该函数被触发时,它应该更新我的状态,从而重新渲染我的内容组件。但是,它不起作用。我的控制台中也没有出现任何错误。它只是什么也没做。
这是我的选项卡(容器)
import * as React from 'react';
import Sidebar from './Sidebar';
import Content from './Content';
import './css/Tabs.css';
export interface State {
message: string;
}
class Tabs extends React.Component<{}, State> {
public state: State = {
message: 'Select a name from the tabs menu',
};
componentWillMount () {
if ('pluginLoaded' in window) {
(window as any).pluginLoaded('hello', function (port: any, context: any) {
// Future work should interact with the message channel here
});
}
}
handleName(value: string) {
if (value === 'Vanessa') {
this.setState({
message: 'Vanessa means "butterfly"'
});
} else if (value === 'Paola') {
this.setState({
message: 'Paola means "small"'
});
}
}
render() {
return (
<div className="Tabs">
<p>Tabs</p>
<Sidebar handleName={() => this.handleName}/>
<Content message={this.state.message}/>
</div>
);
}
}
export default Tabs;
这是我的侧边栏
import * as React from 'react';
export interface Props {
handleName: (value: String) => void;
}
const Sidebar: React.StatelessComponent<Props> = (props) => {
// declare constants
const Vanessa = 'Vanessa',
Paola = 'Paola';
return(
<div className="Sidebar">
<h1>Tabs</h1>
<ul>
<li><a onClick={() => props.handleName(Vanessa)}>Vanessa</a></li>
<li><a onClick={() => props.handleName(Paola)}>Paola</a></li>
</ul>
</div>
);
};
export default Sidebar;
这是我的内容
import * as React from 'react';
export interface Props {
message: string;
}
const Content: React.StatelessComponent<Props> = (props) => {
return(
<div className="Content">
<h1>Find the meaning</h1>
<p>{props.message}</p>
</div>
);
};
export default Content;
最佳答案
改变
<Sidebar handleName={() => this.handleName}/>
至
<Sidebar handleName={this.handleName}/>
还使用箭头函数将handleName
绑定(bind)到类范围
handleName = (value: string) => {
关于javascript - 在 React + TypeScript 中将函数从容器传递到功能组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46477657/