反应-从道具调用功能

时间:2020-02-26 09:58:49

标签: javascript reactjs

我尝试通过子代树从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}

                                                      /> }
                                                      />                                     

App的子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>

1 个答案:

答案 0 :(得分:0)

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);
      }
    };