[英]Reactjs pass state as props to child
我开始学习React。 我已经看过react网站https://reactjs.org/docs/hello-world.html的教程,但有时,所有道具概念对我来说都不起作用。
我的程序崩溃了,错误消息是:
为什么会发生? 有人可以帮我吗?
TypeError:无法读取未定义onSetColor 8的属性“ handleSetColor” ColorDisplay类扩展了Component {9 | 10 | onSetColor(newColor){
11 | this.handleSetColor(newColor); 12 | }
import React, { Component } from 'react';
import './App.css';
import _ from 'underscore';
import PropTypes from 'prop-types';
class ColorDisplay extends Component {
onSetColor(newColor) {
this.props.handleSetColor(newColor);
}
render() {
return (<p>
<input type="color" value={this.props.val} onChange={this.onSetColor} />
</p>);
}
}
ColorDisplay.propTypes = {
handleSetColor: PropTypes.func,
val: PropTypes.string,
};
function TextDisplay(props) {
return <input type="text" value={props.val} readOnly={true} />
}
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
showColorDisplay: true,
showTextDisplay: true,
val: '#ffff00',
}
}
randomizeColor = (e) => {
this.setState(oldState => ({
val: _.sample(['#ffff00', '#ff00ff', '#abff01', '#10f100', '#3030ff', '#ddcc10']),
}));
}
toggle(val) {
this.setState(oldState => ({ [val]: !oldState[val] }));
}
setColor(newColor) {
this.setState({ val: newColor });
}
toggleColorDisplay = (e) => {
this.toggle('showColorDisplay');
}
toggleTextDisplay = (e) => {
this.toggle('showTextDisplay');
}
render() {
return (
<div className="spaced">
<h1>HELLO</h1>
<button onClick={this.randomizeColor}>Shuffle</button><br />
<label>
<br />
<input type="checkbox" checked={this.state.showColorDisplay} onChange={this.toggle.bind(this, 'showColorDisplay')} />
Color Display
</label>
<label>
<input type="checkbox" checked={this.state.showTextDisplay} onChange={this.toggle.bind(this, 'showTextDisplay')} />
Text Display
</label>
<div className="spaced">
{this.state.showColorDisplay && <ColorDisplay val={this.state.val} handleSetColor={this.setColor} />}
</div>
<div className="spaced">
{this.state.showTextDisplay && <TextDisplay val={this.state.val} />}
</div>
</div>
);
}
}
您需要调用Component
构造函数并绑定onSetColor
的范围:
class ColorDisplay extends Component {
constructor(props) {
// This calls the constructor for React.Component
super(props);
// you also need to explicitly bind the scope
this.onSetColor = this.onSetColor.bind(this);
}
onSetColor(newColor) {
this.props.handleSetColor(newColor);
}
render() {
return (<p>
<input type="color" value={this.props.val} onChange={this.onSetColor} />
</p>);
}
}
我现在无法复制问题,但是为了以防万一,我会尝试将该方法绑定到Color Display。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.