我尝试通过子代树从props调用函数addPost,但看到“ props.addPost不是函数”错误,我建议这是上下文的丢失,并尝试使用具有绑定但结果相同的类组件。
state.js
...
export let addPost = (postMessage) =>{
let newPost = {
link: 'www.google.com',
img: 'https://arthomework.ru/upload/iblock/b63/b63c8ab62c0250037748e471e2fac87f.jpg',
alt: 'racoon',
text: postMessage,
count: '0',
id: 4
};
state.profilePage.postItems.push(newPost);
rerenderEntireTree(state);
}
export default state;
App.js
<Route path="/profile" render={ ()=> <Profile
state={props.state.profilePage}
addPost={props.addPost}
/> }
/>
应用的子Profile.jsx
const Profile = (props) =>{
return(
<div>
<MyPosts posts={props.state.postItems} addPost={props.addPost} />
</div>
)
}
下一个孩子
const MyPosts = (props) =>{
let newPost = React.createRef();
let addPost = (props) =>{
let text = newPost.current.value;
try{
props.addPost(text);
} catch(e){
alert('Ошибка ' + e.name + ":" + e.message + "\n" + e.stack);
}
};
return(
<div className="posts">
<div className={classes.title}>My posts</div>
<form action="" className={classes.form}>
<textarea
name="posts"
placeholder="your news..."
className={classes.textarea}
ref={newPost}
>
</textarea>
<button className={classes.button} value="Send" onClick={addPost}> </button>
</form>
最佳答案
在addPost
组件的MyPosts
方法上,您希望将props作为参数,而不是获取事件本身,并且显然其中没有addPost
函数。
// no parameter needed here.
let addPost = () =>{
let text = newPost.current.value;
try{
props.addPost(text);
} catch(e){
alert('Ошибка ' + e.name + ":" + e.message + "\n" + e.stack);
}
};
关于javascript - react -从 Prop 调用功能,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60411230/