我无法找出为什么我的onClick
事件无法在我的React应用程序中正常工作。
我正在尝试div
用字母表中的字母创建s行。div
单击s之一时,div
应将其及其字母从行中删除。
我已经将该onClick
事件div
作为状态中字母字符串映射的一部分附加到s上,但是我似乎丢失/忽略了一些东西,因为我根本无法单击div
s。
我确保将函数绑定到构造函数中。
let { Grid, Row, Col } = ReactBootstrap;
class Letter extends React.Component {
render () {
const style = { border: '1px solid black',
display: 'inline-block',
fontSize: '4vw',
width: '4vw',
height: '8vh',
textAlign: 'center'};
return (<div style={style} key={this.props.key}>
{this.props.letter}
</div>);
}
}
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
alpha: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
};
this.callLetter = this.callLetter.bind(this);
}
callLetter(e) {
var letterindex = this.state.alpha.indexOf(e.currentTarget.attributes[0].value);
var alphaclone = this.state.alpha;
alphaclone = alphaclone.slice(0, letterindex) + alphaclone.slice(letterindex + 1);
this.setState({alpha:alphaclone});
}
render() {
return (
<Grid>
<Row className="show-grid" >
{this.state.alpha.split('').map((item, i) =>
(
<Letter letter = {item} key = {i} onClick = {this.callLetter}/>
))}
</Row>
</Grid>
);
}
}
ReactDOM.render(
<MyComponent/>,
document.getElementsByClassName('container-fluid')[0]
);
谢谢。
您需要添加onClick
到Letter组件中。
(您的Letter组件获得一个onClick道具,但未使用它。)
class Letter extends React.Component {
render () {
const style = { border: '1px solid black',
display: 'inline-block',
fontSize: '4vw',
width: '4vw',
height: '8vh',
textAlign: 'center'};
return (
<div
style={style}
key={this.props.key}
onClick={this.props.onClick} // Have to pass onClick to div
>
{this.props.letter}
</div>
);
}
}
发生的是onClick是只有DOM元素才知道的属性。虽然信是一种反应组件创建,所以你需要指定做什么用的onClick
<Letter letter={item} key={i} onClick={this.callLetter}/>
注意:上面的代码仅解决了确保onClick被处理的问题。您现在要做的是通过使Letter组件处理事件来确保callLetter获得正确的字母。
class Letter extends React.Component {
onHandleClick = () => {
this.props.onClick(this.props.letter);
};
render () {
const style = { border: '1px solid black',
display: 'inline-block',
fontSize: '4vw',
width: '4vw',
height: '8vh',
textAlign: 'center'};
return (
<div
style={style}
key={this.props.key}
onClick={this.onHandleClick} // Have to pass onClick to div
>
{this.props.letter}
</div>
);
}
}
为您的callLetter更改参数以使用字母。
callLetter(letter) {
var letterindex = this.state.alpha.indexOf(letter);
var alphaclone = this.state.alpha;
alphaclone = alphaclone.slice(0, letterindex) + alphaclone.slice(letterindex + 1);
this.setState({alpha:alphaclone});
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句