javascript - React - 从 props 调用函数

标签 javascript reactjs

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

相关文章:

reactjs - 有没有办法避免使用 Tailwind 清除特定库?

javascript - 绝对初学者 React 按钮 Axios

javascript - 带有禁用字段的 Angular 表单验证

javascript - 针对 globar var 的私有(private) var 当全局改变时不改变

reactjs - ReactJS 和 .NET Core API 中的 windows 授权

javascript - 如何在选择组件中按下选项的第一个字母时禁用项目的选择?

javascript - Bootstrap : Why isnt my glyphicon showing?

reactjs - 无法转到完整日历上的特定日期

javascript - JavaScript 中的执行上下文和对象

javascript - 将一个 div 类放在 three.js 场景之上以创建一个 gui