Javascript 反应-在这种情况下,如何在输入组件中设置状态?
我有两个组件:Javascript 反应-在这种情况下,如何在输入组件中设置状态?,javascript,reactjs,Javascript,Reactjs,我有两个组件:输入和按钮 输入代码: import React, { Component } from 'react'; import TextField from 'material-ui/TextField'; import './style.css'; import Buttons from '../Buttons'; class Input extends Component { constructor(props) { super(props); this.st
输入
和按钮
输入
代码:
import React, { Component } from 'react';
import TextField from 'material-ui/TextField';
import './style.css';
import Buttons from '../Buttons';
class Input extends Component {
constructor(props) {
super(props);
this.state = {
password: '',
selectedButtons: [],
};
}
handleInputChange(pass) {
this.setState({ password: pass });
}
handleButtonSelectTwo(selected) {
// this.setState({ selectedButtons: selected });
console.log(selected);
}
render() {
return (
<div>
<div className="Input-textfield">
<TextField
hintText="Paste your password here to begin"
value={this.state.password}
onChange={event => this.handleInputChange(event.target.value)}
/>
</div>
<div>
<Buttons handleButtonSelectOne={this.handleButtonSelectTwo} />
</div>
</div>
);
}
}
export default Input;
import React from 'react';
import RaisedButton from 'material-ui/RaisedButton';
const style = {
button: {
margin: 2,
padding: 0,
minWidth: 1,
},
};
const Buttons = props => {
const arr = [
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
];
const handleButtonSelectZero = props.handleButtonSelectOne;
const allButtons = arr.map(el => (
<RaisedButton
key={el}
label={el}
style={style.button}
onClick={() => handleButtonSelectZero(el)}
/>
));
return <div>{allButtons}</div>;
};
export default Buttons;
问题是关于把手按钮selecttwo
功能。因此,对于console.log,它是有效的。例如,当我单击按钮11时,它会打印到控制台“11”。我的理解是,handleButtonSelectTwo
函数作为一个道具传递给Buttons
child,并在那里启动
在这种情况下,如果我现在想将这样的代码添加到handleButtonSelectTwo
insideInput
组件中:
handleButtonSelectTwo(selected) {
this.setState({ selectedButtons: selected });
}
它将无法工作,因为它将在属于无状态组件的按钮
组件内激发
所以,如果我想在我的Input
组件中有被点击的数据,我该怎么做呢
在我的Input
组件中,我的状态如下:
constructor(props) {
super(props);
this.state = {
password: '',
selectedButtons: [],
};
}
我希望它由我点击的按钮填充
有什么简单的方法可以做到这一点吗?(例如,不使用redux)您可能需要绑定
把手按钮选择两个以正确此
。在Input
组件的构造函数中,输入this.handleButtonSelectTwo=this.handleButtonSelectTwo.bind(this)
快速建议:您可能需要绑定handleButtonSelectTwo
以获得正确的this
上下文。在Input
组件的构造函数中,输入this.handleButtonSelectTwo=this.handleButtonSelectTwo.bind(this)
Thx、@Varinder,现在它可以工作了!亲爱的,很乐意帮忙,我把这句话作为对你的回答,这句话已经回答了无数次了。请寻找副本,而不是回答。