简体   繁体   中英

How can i pass props through methods inside components?

i have a react component named "List" that renders smaller components "Post" using a button through method "Addpost()" that takes 2 props from the input form. I have saved the input in 2 varables but i don't know how to pass these props to the Addpost() method inside the return of List's render().

//=========== List component ==============

class List extends React.Component{

renderPost(title,content){
    return(
        <Post titolo={title} contenuto={content}/>
    );
}

renderPost just render the Post component in a in the HTML

 addPost(title,content){
     title = document.getElementById("inputTitle").value;
     content = document.getElementById("inputContent").value;
    console.log(title, content)
    this.renderPost(title,content);
}

addPost should take the input value and use renderPost to render the Post component with that title and content

    render(){
        return(
            <div>
          {this.renderPost("testTitle","testContent")}

       <form> 
             Title:<br></br>
             <input type="text" id="inputTitle"/><br></br>
             Content:<br></br>
             <input type="text" id="inputContent"/>
       </form><br></br>
       <button className="square"

how can i make this work? title and content are not defined

 onClick={() => 
               this.addPost(title,content)
               Add Post!
       </button>

           </div>     

        );
    }
}

//=========== Post component ==============

class Post extends React.Component {

  render() {
    return (
      <li className="w3-padding-16">
      <img src="/w3images/workshop.jpg" alt="Imagedf" className="w3-left w3-margin-right" />`enter code here`
      <span className="w3-large">
        {this.props.titolo}
      </span><br></br>
      <span>{this.props.contenuto}</span>
    </li>
    );
  }
}

Basically, whenever you're dealing with forms and inputs, you would use refs .

App.js

import React from 'react';
import logo from './logo.svg';
import './App.css';
import PostList from './components/PostList'
import AddPostForm from './components/AddPostForm'

class App extends React.Component {

  constructor(props) {
    super(props)
    this.state = {
      posts: [] //state is handled here
    }

    this.addPost = this.addPost.bind(this)
  }

  addPost(title, content) {
    let newPost = { title, content }
      this.setState(({ posts }) => { return { posts: [...posts, newPost] } } )
  }

  render() {

    const { posts } = this.state

    return (
      <div>
        <AddPostForm onNewPost={this.addPost} /> //we pass addPost to the component
        <br />
        <PostList posts={posts} />
      </div>
    );
  }
}

export default App;

Post.js

import React from 'react';

function Post({titolo, contenuto}) {
    return (
      <li className="w3-padding-16">
      <img src="/w3images/workshop.jpg" alt="Imagedf" className="w3-left w3-margin-right" />`enter code here`
      <span className="w3-large">
        {titolo}
      </span><br></br>
      <span>{contenuto}</span>
    </li>
    );
}

export default Post

AddPostForm.js

import React from 'react';

const addPostForm = ({onNewPost = f => f}) => { //onNewPost method is passed by props from the parent
    let _titleInput, _contentInput //these are our refs, see the docs for more information

    const submit = (e) => {
        e.preventDefault()
        onNewPost(_titleInput.value, _contentInput.value) //here we call the addPost function that was passed to the component
        _titleInput.value = '' //empty the inputs
        _contentInput.value = ''
        _titleInput.focus() //set focus
    }

    return (
        <form onSubmit={submit}>
            Title:<br></br>
             <input type="text" ref={title => _titleInput = title} /><br></br>{/* Note the ref attribute */}
             Content:<br></br>
             <input type="text" ref={content => _contentInput = content} />
             <button className="square">Add a new post</button>
        </form>
        )
}

export default addPostForm

PostList.js

import React from 'react';
import Post from './Post';

const PostList = ({ posts=[] }) => {
    return (
        <div className="post-list">
            {
                posts.map((post, index) => 
                    <Post key={index} titolo={post.title} contenuto={post.content} />
                )
            }
        </div>
    )
}

export default PostList

And the result:

结果

edit

renderPost just render the Post component in a in the HTML

 state = { inputTitle: '', inputContent: '' }

 addPost(title,content){
     title = document.getElementById("inputTitle").value;
     content = document.getElementById("inputContent").value;
    console.log(title, content)
    this.renderPost(title,content);
}

addPost should take the input value and use renderPost to render the Post

component with that title and content

    render(){
        return(
            <div>
          {this.renderPost("testTitle","testContent")}

       <form> 
             Title:<br></br>
             <input type="text" value={this.inputTitle} onChnage={event => setState({ inputTitle: event.target.value }) }><br></br>
             Content:<br></br>
             <input type="text" value={this.inputContent} onChnage={event => setState({ inputContent: event.target.value }) } />
       </form><br></br>
       <button className="square"

on click function

 onClick={() => 
               this.addPost(this.inputTitle,this.inputContent)
               Add Post!
       </button>

           </div>     

        );
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM