问题:我想按下“机械手”类按钮,将ChangeValue的值变量更改为机械手的manipulatorName值,这是没有发生的。我做错什么了?
我有一个类(名为ChangeValue),它用空字符串名初始化。我这样做,因为它将在网站上显示为“空”暂时。但是,当我单击另一个类(称为机械手)时,它应该会更改ChangeValue,这是没有发生的。ChangeValue的值总是设置为“空”,尽管当我单击该按钮时。
我的代码:
export class ChangeValue extends React.Component {
constructor(props) {
super(props)
this.state = {
value: " "
};
}
render() {
var currentValue = null;
if (this.value == null) {
currentValue = "Empty"
} else {
currentValue = this.value
}
return (
currentValue
)
}
}export class Manipulator extends React.Component {
constructor(props) {
super(props)
this.state = {
manipulatorName: "New Value"
};
this.handleClick = this.handleClick.bind(this);
}
render() {
return (
<button onClick = {this.handleClick}>
<ChangeValue value = {this.state.manipulatorName} />
</button>
)
}
}我基于我从Stack上读到的"ChangeValue值“行,可能父母/孩子也有问题?
发布于 2019-11-20 23:51:32
关于为什么它不起作用,这里发生了一些事情。
您可以清理ChangeValue组件,因为它实际上不使用任何状态。它只需要使用从Manipulator传递给它的支柱的值,因此可以将其转换为基于“哑”函数的无状态组件。
function ChangeValue(props) {
return props.value || "Empty"
}或者如果你仍然希望它是一个类,那么你可以在以后添加一些状态.
export class ChangeValue extends React.Component {
render() {
return this.props.value || "Empty"
}
}它们将具有相同的输出。如果props.value是特鲁西,则返回props.value的值;如果props.value是虚妄,则或 (||)返回单词“props.value”。
Manipulator类也需要一些工作。它目前设置了一个handleClick方法,但没有定义它。应该像这样..。
export class Manipulator extends React.Component {
constructor(props) {
super(props);
this.state = {
manipulatorName: undefined
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState({
manipulatorName: "New Value After Click"
});
}
render() {
return (
<button onClick={this.handleClick}>
<ChangeValue value={this.state.manipulatorName} />
</button>
);
}
}这将首先呈现一个带有文本“空”的按钮,因为manipulatorName是*falsy*。单击按钮后,按钮文本应更改为“单击后的新值”。
我希望这有帮助,如果它不完全符合您正在努力实现的,请评论或更新问题的一些进一步的细节。
更新
这是一个CodeSandbox上的工作实例。
https://stackoverflow.com/questions/58964859
复制相似问题