【问题标题】:React - call function from propsReact - 从道具调用函数
【发布时间】:2020-02-26 09:58:49
【问题描述】:

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

标签: javascript reactjs


【解决方案1】:

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

【讨论】:

  • 我该如何解决?
猜你喜欢
  • 2021-01-09
  • 2020-07-04
  • 1970-01-01
  • 2021-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多