我想在用户点击TopicsList
组件并隐藏SingleTopicBox
组件时显示SelectedTopicPage
组件。但是,我在topic-list.jsx文件中收到错误:Uncaught TypeError: Cannot read property 'bind' of undefined
。
主要-controller.jsx
import {React, ReactDOM} from '../../../build/react';
import TopicsList from '../topic-list.jsx';
import SelectedTopicPage from '../selected-topic-page.jsx';
import topicPages from '../../content/json/topic-pages.js';
export default class MainController extends React.Component {
state = {
isTopicClicked: false,
topicPages
};
onClick(topicID) {
this.setState({isTopicClicked: true});
this.setState({topicsID: topicID});
};
render() {
return (
<div className="row">
{this.state.isTopicClicked
? <SelectedTopicPage topicsID={this.state.topicsID} key={this.state.topicsID} topicPages={topicPages}/>
: <TopicsList/>}
</div>
);
}
};
主题的list.jsx
import {React, ReactDOM} from '../../build/react';
import SingleTopicBox from './single-topic-box.jsx';
import SelectedTopicPage from './selected-topic-page.jsx';
import topicPages from '../content/json/topic-pages.js';
export default class TopicsList extends React.Component {
onClick(){
this.props.onClick.bind(null, this.topicID);
},
render() {
return (
<div className="row topic-list">
<SingleTopicBox topicID="1" onClick={this.onClick} label="Topic"/>
<SingleTopicBox topicID="2" onClick={this.onClick} label="Topic"/>
<SingleTopicBox topicID="3" onClick={this.onClick} label="Topic"/>
<SingleTopicBox topicID="4" onClick={this.onClick} label="Topic"/>
</div>
);
}
};
单主题-box.jsx
import {React, ReactDOM} from '../../build/react';
export default class SingleTopicBox extends React.Component {
render() {
return (
<div>
<div className="col-sm-2">
<div className="single-topic" data-topic-id={this.props.topicID}>
{this.props.label} {this.props.topicID}
</div>
</div>
</div>
);
}
};
答案 0 :(得分:2)
你有几个错误
您应该将onClick
传递给TopicsList
render() {
return (
<div className="row">
{this.state.isTopicClicked
? <SelectedTopicPage
topicsID={this.state.topicsID}
key={this.state.topicsID}
topicPages={topicPages} />
: <TopicsList onClick={ this.onClick.bind(this) } />}
</div>
);
}
从onClick
TopicsList
方法
onClick() {
// ...
},
从onClick
props
回调
<SingleTopicBox topicID="1" onClick={this.props.onClick} label="Topic"/>
添加到SingleTopicBox
onClick
活动
<div
className="single-topic"
data-topic-id={this.props.topicID}
onClick={ () => this.props.onClick(this.props.topicID) }
>
{this.props.label} {this.props.topicID}
</div>
您不需要两次致电setState
onClick(topicID) {
this.setState({
isTopicClicked: true,
topicsID: topicID
});
}