我正在尝试将App.js中的onSearchChangeEvent()函数作为函数传递给Searchbox组件,但出现错误提示
预期
onChange
侦听器为一个函数,但其值为object
类型。
我在Stackoverflow上查找了针对同一错误的不同答案,但无法解决此问题。
App.js:包含函数 onSearchChangeEvent(),我试图传递给
import React, {Component} from 'react';
import Cardlist from './Cardlist';
import Searchbox from './Searchbox';
import {robots} from './robots';
class App extends Component {
constructor () {
super()
this.state = {
robots : robots,
searchfield : ''
}
}
onSearchChangeEvent = () => {
console.log("Something Happened");
}
render () {
return (
<div className='tc'>
<h1>Robo Friends</h1>
<Searchbox searchChange={() => this.onSearchChangeEvent}/>
<Cardlist robots={this.state.robots} />
</div>
);
}
}
export default App;
Searchbox.js
import React from 'react';
const Searchbox = (searchField, searchChange) => {
return (
<div className='pa2'>
<input
className='pa3 ba b--green bg-lightest-blue'
type='search'
placeholder='Search Robots'
onChange={searchChange}
/>
</div>
);
}
export default Searchbox;
错误:首先,我得到警告,当事件触发时,我得到错误
答案 0 :(得分:2)
您在php.ini
组件中无法正确访问道具。您需要解构它们,而不是将它们定义为参数
SearchBox
然后像
一样传递const Searchbox = ({ searchField, searchChange }) => {
return (
<div className='pa2'>
<input
className='pa3 ba b--green bg-lightest-blue'
type='search'
placeholder='Search Robots'
onChange={searchChange}
/>
</div>
);
}
或
<Searchbox searchChange={this.onSearchChangeEvent}/>
尽管您必须使用 <Searchbox searchChange={() => this.onSearchChangeEvent()}/>
,因为在定义<Searchbox searchChange={this.onSearchChangeEvent}/>
函数时您已经在使用箭头功能