单击 React js 中的按钮时如何获得innerHTML?

Jay*_*Jay 5 javascript reactjs

我正在尝试使用material-ui-flat-pagination。由于该库在单击上一个或下一个按钮时似乎不提供页码,因此我试图自己获取该值。它只提供了一个onClickprop,所以我曾经event.target得到我点击的值。

在此处输入图片说明

event.target显示了上面的标签,我需要3span 标签内的值。如何在 React js 中获取值?我是否正在接近使用库material-ui-flat-pagination获取页码的正确方法?

JVa*_*ake 6

我很抱歉没有添加评论,我还没有声誉。x 会记录您要询问的数字,但不要尝试使用 x 更新偏移量,这是在模块的 core.ts 上定义的偏移量计算的原因。

export const getOffset = (page: number, limit: number): number => { const offset = (page - 1) * limit; return offset < 0 ? 0 : offset; };

虽然你可以尝试通过解析事件来获取你想要的 HTML。一个技巧是将案例与界面提供的参数相匹配,例如下一个或上一个标签

e.target.innerText
e.currentTarget.childNodes[0].innerText
Run Code Online (Sandbox Code Playgroud)

*注意它是一个字符串所以关心你的数字比较

import React from "react";
import ReactDOM from "react-dom";
import CssBaseline from "@material-ui/core/CssBaseline";
import { createMuiTheme, MuiThemeProvider } from "@material-ui/core/styles";
import Pagination from "material-ui-flat-pagination";

const theme = createMuiTheme();

class Example extends React.Component {
constructor(props) {
    super(props);
    this.state = { offset: 0, limit: 3, total: 132, calc: 1, nlabel: ">>", plabel: "<<" };
}

handleClick(e, offset) {
    let y = e.target.innerText; 
    //let y =e.currentTarget.childNodes[0].innerText;

    if (y === this.state.plabel) y = Number(this.state.calc) - 1;
    if (y === this.state.nlabel) y = Number(this.state.calc) + 1;
    let x = offset / this.state.limit + 1;
    console.log("x:" + x + " - y:" + y);
    this.setState({ offset, calc: y });
}

render() {
    return (
        <MuiThemeProvider theme={theme}>
            <div>{this.state.offset}</div>
            <div>{this.state.calc}</div>
            <CssBaseline />
            <Pagination
                limit={this.state.limit}
                offset={this.state.offset}
                total={this.state.total}
                onClick={(e, offset) => this.handleClick(e, offset)}
                nextPageLabel={this.state.nlabel}
                previousPageLabel={this.state.plabel}
            />
        </MuiThemeProvider>
    );
}
}

ReactDOM.render(<Example />, document.getElementById("root"));
Run Code Online (Sandbox Code Playgroud)