Reputation: 27
I'm learning React and was trying to write a program which shows the Unicode of the pressed key on screen. No error popped up but the state( pressed key and Unicode) wasn't printed on the screen, either ( the state changed accordingly well). The props were set but it's not working.
The code(Javascript):
const key = props=>{
return (<p className="key" onTransitionEnd={props.transitionHandle}>{props.key}</p>);
}
const charCode = props=>{
return (<p className="charCode">{props.charCode}</p>);
}
class App extends React.Component{
constructor(props){
super(props);
this.state = {key: "A", charCode: "65"}
this.keydownHandle = this.keydownHandle.bind(this);
document.addEventListener("keydown",function(event){
this.keydownHandle(event);
}.bind(this));
}
render(state){
return (
<div className="box">
<charCode charCode={this.state.charCode}></charCode>
<key onTransitionEnd={this.transitionHandle} key={this.state.key}></key>
</div>
);
}
keydownHandle(event){
this.setState({
key: String.fromCharCode(event.keyCode),
charCode: event.keyCode
});
}
transitionHandle(){
document.getElementsByClassName("key").classList.remove("pressed");
}
}
ReactDOM.render(<App/>,document.querySelector(".container"));
Thanks a lot.
Upvotes: 1
Views: 4023
Reputation: 161
Couple of things
key
is one of the special attributes that cannot be passed as props (source: https://facebook.github.io/react/docs/lists-and-keys.html)
User defined components must be capitalized - use Key
and CharCode
instead of key
and charCode
(source: https://facebook.github.io/react/docs/jsx-in-depth.html#user-defined-components-must-be-capitalized)
Upvotes: 1