我尝试通过子树从 props 调用函数 addPost ,但看到“props.addPost 不是函数”错误,我建议这是上下文丢失,并尝试使用带有绑定(bind)的类组件,但结果相同。
状态.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>
)
}
下一个 child
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>
最佳答案
在 MyPosts
组件的 addPost
方法上,您期望 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 - 从 props 调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60411230/