Reactjs 在react中,在没有组件安装的情况下,如何在具有setState的函数内调用函数?

Reactjs 在react中,在没有组件安装的情况下,如何在具有setState的函数内调用函数?,reactjs,Reactjs,我尝试在绑定函数中使用函数,使用中给出的答案。我还尝试使用JSON.stringify“const data”。我可以打印按钮,但我正在尝试将单击的按钮存储在值中 const InitArr = ({ myArray, handleClick }) => ( <div> {myArray.map(item => (<button onClick={() => handleClick(item.key)}>{item.key}</button>

我尝试在绑定函数中使用函数,使用中给出的答案。我还尝试使用JSON.stringify“const data”。我可以打印按钮,但我正在尝试将单击的按钮存储在值中

const InitArr = ({ myArray, handleClick }) => ( <div> {myArray.map(item => (<button onClick={() => handleClick(item.key)}>{item.key}</button> ))}    </div>)
class App extends React.Component {
   constructor(props) {
     super(props);
     this.state = {myArray: [{"key": "7"},{"key": "8"},{"key": "9"},{"key": "4"},{"key": "5"},{"key": "6"},{"key": "1"},{"key": "2"},{"key": "3"},{"key": "0"}], value: '0', };
     this.setValues = this.setValues.bind(this)
     this.handleClick = this.handleClick.bind(this)
   }
   setValues(key) {
      const temp = key
   }
   handleClick(key) {
       const { value } = this.state
       const data = setValues(key)
       this.setState({ value: data })
    }
    render() {
    return (
       <div>
          <div>{this.state.value}</div>
              <InitArr myArray={this.state.myArray} handleClick={this.handleClick} />
       </div>
     );}}
     ReactDOM.render( <App />, document.getElementById("root"));
const InitArr=({myArray,handleClick})=>({myArray.map(item=>(handleClick(item.key)}>{item.key})))
类应用程序扩展了React.Component{
建造师(道具){
超级(道具);
this.state={myArray:[{“key”:“7”},{“key”:“8”},{“key”:“9”},{“key”:“4”},{“key”:“5”},{“key”:“6”},{“key”:“1”},{“key”:“2”},{“key”:“3”},{“key”:“0”},值:'0';
this.setValues=this.setValues.bind(this)
this.handleClick=this.handleClick.bind(this)
}
设置值(键){
常数温度=键
}
把手舔(键){
const{value}=this.state
常量数据=设置值(键)
this.setState({value:data})
}
render(){
返回(
{this.state.value}
);}}
render(,document.getElementById(“根”));

您的代码的问题是您调用的是
setValues(key)
而不是
this.setValues(key)
,因此它在当前范围内找不到
setValues

更改允许代码运行,但我也更改了setValue以返回某些内容,这样渲染的数字就不会消失:

setValues(key) {
    const temp = key;
    return key;
  }
const InitArr=({myArray,handleClick})=>(
{' '}
{myArray.map((项)=>(
handleClick(item.key)}>{item.key}
))}{' '}
);
类应用程序扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
myArray:[
{键:'7'},
{键:'8'},
{键:'9'},
{键:'4'},
{键:'5'},
{键:'6'},
{键:'1'},
{键:'2'},
{键:'3'},
{键:'0'},
],
值:“0”,
};
this.setValues=this.setValues.bind(this);
this.handleClick=this.handleClick.bind(this);
}
设置值(键){
const temp=键;
返回键;
}
把手舔(键){
const{value}=this.state;
控制台日志(键);
const data=此.setValues(键);
this.setState({value:data});
}
render(){
返回(
{this.state.value}
);
}
}
ReactDOM.render(,document.getElementById('root'))


当点击发生时,您希望看到什么行为?您的问题是什么?
设置值的目的和/或意义是什么?它返回undefined。您能提供更多的上下文吗?尝试打印按钮,然后单击“存储在值中”。如果您简单地关闭
设置状态
…,按钮将继续打印?同时将它们存储在字符串中。我仍然认为没有足够的上下文和信息来准确回答问题。OP甚至没有明确说明问题所在。对于这个解决方案,您可以只使用
this.setState({value:key})
并跳过不起任何作用的
setValues
函数。好吧,我想它解决了一些问题。