总体目标是根据输入调用菜谱。
我试图从我将其作为 Prop 传递给的 child 中调用父级中的 search() 。但我收到错误 - TypeError: this.props.search is not a function
任何人都可以看到我错在哪里:/我已经处理了绑定(bind)并传递了 Prop :/
来自父级的代码
import React, { Component } from 'react';
import RecipeDisplay from '../RecipeDisplay/RecipeDisplay';
import Form from '../Form/Form';
import './RecipeUI.css';
export default class RecipeUI extends Component {
constructor(props) {
super(props);
this.state = {
RecipeUI: [
{
heading: 'heading!',
img:
'https://d2qpatdq99d39w.cloudfront.net/wp-content/uploads/2019/05/08152013/food-addiction-2.jpg',
ingridients: 'ingridients',
link:
'https://d2qpatdq99d39w.cloudfront.net/wp-content/uploads/2019/05/08152013/food-addiction-2.jpg'
}
]
};
this.search = this.search.bind(this);
}
search() {
alert('oi');
}
render() {
return (
<div className="RecipeUI">
<div className="RecipeUI-header">
<h1>Welcome to the Recipe Fetcher</h1>
<Form />
</div>
<div className="RecipeUI-RecipeDisplay">
{this.state.RecipeUI.map((recipe) => (
<RecipeDisplay
heading={recipe.heading}
img={recipe.img}
ingridients={recipe.ingridients}
link={recipe.link}
search={this.search}
/>
))}
</div>
</div>
);
}
}
来自 child 的代码
import React, { Component } from 'react';
export default class Form extends Component {
constructor(props) {
super(props);
this.state = { recipeinput: '' };
this.handleInput = this.handleInput.bind(this);
this.handleSearch = this.handleSearch.bind(this);
}
handleInput(e) {
this.setState({ [e.target.name]: e.target.value });
}
handleSearch(e) {
e.preventDefault();
this.props.search();
}
render() {
return (
<div>
<form>
<label htmlFor="recipeinput">What are you in the mood for today?</label>
<input
id="recipeinput"
name="recipeinput"
value={this.state.recipeinput}
onChange={this.handleInput}
/>
</form>
<button onClick={this.handleSearch}>Search</button>
</div>
);
}
}
最佳答案
您的表单组件尚未收到任何 Prop 。相反,您已将 this.search
传递到 RecipeDisplay 组件中。
render() {
return (
<div className="RecipeUI">
<div className="RecipeUI-header">
<h1>Welcome to the Recipe Fetcher</h1>
<Form search={this.search} />
</div>
<div className="RecipeUI-RecipeDisplay">
{this.state.RecipeUI.map((recipe) => (
<RecipeDisplay
heading={recipe.heading}
img={recipe.img}
ingridients={recipe.ingridients}
link={recipe.link}
/>
))}
</div>
</div>
);
}
关于javascript - 在 react 中从子级调用父级中的函数时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60773480/