javascript - React 通过 onclick 调用组件

标签 javascript jquery reactjs

各位伟大的程序员大家好

感谢您阅读我的问题

。我在 react 库中的问题是我想通过单击调用另一个组件。

如果您看到代码,我已通过//******** 提供了必要的解释

<pre>class CategoryList extends React.Component {
constructor(props) {
    super(props);
    this.state = {
        id: 0, name: "", title: "", description: "", subTitle: "", imagePath: "", tags: "",
        data: [],
        pageInfo: []
    };
}

componentDidMount() {
// read data is ok
}

renderCategories() {
// this function is ok
        return this.state.data.map(category => {
            return (
                <tr id={"one-row-" + category.id} key={category.id}>
                    <td>{category.id}</td>
                    <td>{category.name}</td>
                    <td>{category.title}</td>
                    <td>{category.description}</td>
                    <td>
                        <a className="btn btn-primary btn-sm" data-toggle="modal" href="#edit-modal" title="EDIT" onClick={(e) => this.editCategory(category)}>

                        EDIT</a>
                </td>
            </tr>
        )
    })
}

render() {
// this function is ok
        var ReturnView =
            <div>
                <h1 className="text-center">Categories</h1>
                <hr />
            <table className="table table-bordered table-striped table-hovered table-sortable">
                <thead>
                    <tr>
                        <th>id</th>
                        <th>name</th>
                        <th>title</th>
                        <th>desc</th>
                    </tr>
                </thead>

                <tbody>
                    {this.renderCategories()}
                </tbody>
            </table>
        </div>
    return (
        ReturnView
    );
}


editCategory(category) {
    this.setState({
        id: category.id,
        name: category.name,
        title: category.title,
        description: category.description,
        subTitle: category.subTitle,
        imagePath: category.imagePath,
        tags: category.tags,
    }, function () {

// ***************** All My Problems is here *********************
 Category Edit  Component must call here 
        });
    }
}

ReactDOM.render(
    <CategoryList subreddit="catgories" />,
    document.getElementById('root')
);

第二个组件在这里,我需要调用它并将参数发送到该类别编辑组件中进行渲染:

    class CategoryEdit extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            id, name, title, description, subTitle, imagePath, tags
        };
    }

    componentDidMount() {
  //READ DATA FROM SERVER and work
    }

    render() {
        return (
           // CREATE UI and work
        )
    }

    editRow() {
        var id = this.state.id;
        var name = $("#edit-name").val();
        var title = $("#edit-title").val();
        var description = $("#edit-description").val();
        var subTitle = $("#edit-subTitle").val();
        var imagePath = $("#edit-imagePath").val();
        var tags = $("#edit-tags").val();
        $.ajax({
            url: "http://localhost:49384/api/CategoryEdit",
            method: "POST",
            data: {"Id":id, "Name": name, "Title": title, "Description": description, "SubTitle": subTitle, "ImagePath": imagePath, "Tags": tags },
            dataType: "json",
            success: function (result) {
                if (result != null) {
                    alert(result.message);
                    if (result.isSuccess === true) {
                        this.setState({
                            id: id, name: name, title: title, description: description,
                            subTitle: subTitle, imagePath: imagePath, tags: tags
                        });
                    }
                }
            }
        });
    }
}

ReactDOM.render(
    <CategoryEdit />,
    document.getElementById('pop-up-content')
)

我尝试过的:

editCategory(category) {
        this.setState({
            id: category.id,
            name: category.name,
            title: category.title,
            description: category.description,
            subTitle: category.subTitle,
            imagePath: category.imagePath,
            tags: category.tags,
        }, function () {
            <CategoryEdit props="this.state" />
        });
    }

editCategory(category) {
     this.setState({
         id: category.id,
         name: category.name,
         title: category.title,
         description: category.description,
         subTitle: category.subTitle,
         imagePath: category.imagePath,
         tags: category.tags,
     }, function () {
         ReactDOM.render(
             <CategoryEdit props="this.state" />,
             document.getElementById('pop-up-content')
         );
     });
 }

最佳答案

我认为您希望在编辑该类别时单击表中的任何特定类别时呈现新的 editPage 组件。我对吗?如果这是您的问题,那么我将为您提供解决方案。

npm i react-router -s
npm i react-router-dom -s

安装这两个库。

所以这是您的列表组件。 从“react-router-dom”导入{Link};

export class CategoryList extends React.Component {
constructor(props) {
    super(props);
    this.state = {
        data: [],
        pageInfo: []
    };
}

componentDidMount() {
// read data is ok
}

renderCategories() {
// this function is ok
        return this.state.data.map(category => {
            return (
                <tr id={"one-row-" + category.id} key={category.id}>
                    <td>{category.id}</td>
                    <td>{category.name}</td>
                    <td>{category.title}</td>
                    <td>{category.description}</td>
                    <td>
                        <Link
                           className="btn btn-primary btn-sm"
                           to={`/edit/${category.id}`}
                         > 
                           Edit Category
                        </Link>
                </td>
            </tr>
        )
    })
}

这是您的编辑组件:

    class CategoryEdit extends React. Component {
        constructor(props) {
            super(props);
            this.state = {
                id, name, title, description, subTitle, imagePath, tags
            };
        }

        componentDidMount() {
            const id = this.props.match.params.id;
            /*Call server to get details of that catagory using this id. Get response and set the response in your state like:-
       this.setState({title: response.title, description: response.description}) etc. */
        }

        updateCatagory = () => {
          //this is your method to update category with new values in server.
         const {id, name, title, etc..... all params} = this.state;

           $.ajax({
            url: "http://localhost:49384/api/CategoryEdit",
            method: "POST",
            data: {"Id":id, "Name": name, "Title": title, "Description": description, "SubTitle": subTitle, "ImagePath": imagePath, "Tags": tags },
            dataType: "json",
            success: function (result) {
                    this.history.push('/');
              }
          });
        }

        render() {
            return (
               // CREATE UI and work
               //Add a button here.
               <button onClick={this.updateCatagory}>Update Catagory</button>
            )
        }

创建一个新组件index.jsx

import * as React from 'react';
import * as ReactDOM from 'react-dom';
import {Route, BrowserRouter, Switch} from 'react-router-dom';
import {CategoryList} from './your-path-to-component';
import {CategoryEdit} from './your-path-to-component';

    ReactDOM.render(
            <HashRouter>
                <Switch>
                    <Route exact={true} path="/" component={CategoryList}/>
                    <Route exact={true} path="/edit/:id" component={CategoryEdit}/>
                </Switch>
            </HashRouter>,
        document.getElementById('app')
    );
}

关于javascript - React 通过 onclick 调用组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50303892/

相关文章:

javascript - Bootstrap 4 Beta - 使用 ScrollSpy 平滑滚动

javascript - jQuery SerialScroll 循环参数

reactjs - React Navigation "focus"事件监听器不使用更新值

javascript - 无法让 select2 + geonames 一起工作

javascript - 使用d3.js修改c3.js图表

javascript - Microsoft JScript 运行时错误 : Member not found

javascript - 如何在 typescript 中编写遍历列表的函数?

javascript - 打印时无法将 css 文件添加到 html

reactjs - Chakra UI 图像组件无法识别图像路径

javascript - 禁用在按 Tab 键切换到下一个元素时选择语义 UI 下拉选项