簡體   English   中英

保持列表項突出顯示,react.js

[英]Keep a list item highlighted, react.js

我想保留當前單擊列表項的背景顏色和顏色。 我通過以下代碼通過CSS突出顯示了它:

.segmentsList:hover {
    background: black;
    color: white;
    cursor: pointer;
}

我嘗試將onClickFunction附加到li的onClick事件上,如下所示:

import React, {Component} from 'react';
import Link from "react-router-dom/es/Link";
import {Button} from 'reactstrap';
import cabeza from '../atlas/json/cabeza.json';

const parte = getParameterByName('parte') || 0;


export default class SegmentsList extends Component {

    onClickFunction(e) {
        console.log(e);
        // e.target.element.class="newBlackColor";
    }

    render() {


        console.log(cabeza[parte].etiquetas);
        readTextFile(cabeza[parte].etiquetas);

        function readTextFile(url) {
            const rawFile = new XMLHttpRequest();
            rawFile.open("GET", url, false);
            rawFile.overrideMimeType('text/xml; charset=iso-8859-1');
            rawFile.onreadystatechange = function () {
                if (rawFile.readyState === 4) {
                    const text = rawFile.responseText;
                    // console.log(rawFile.responseText);
                    const lines = splitLines(text);
                    // console.log(lines);
                    const words = splitWords(lines[0]);
                    // console.log(words);
                    window.words = words;
                }
                return;

                function splitLines(text) {
                    return text.split('\n');
                }

                function splitWords(line) {
                    return line.split('" "').slice(1);
                }
            };
            rawFile.send();
        }


        return (

            <div>
                <ol>
                    {window.words.map((word, index) =>
                        <li
                            onClick={this.onClickFunction}
                            className='segmentsList'
                            key={index}>{word}</li>
                    )}
                </ol>

                <Button
                    color='primary'
                    className='mt-3 ml-3'
                >
                    <Link to='/'/>
                    Volver a la portada
                </Button>
            </div>

        );
    }
}

function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}

當我單擊列表項時,控制台會顯示:

Uncaught TypeError: Cannot set property 'class' of undefined

並檢查事件對象,我們看到目標為空:

target:null

我究竟做錯了什么?

我也讀過:

CSS更改列表項的背景色(帶類)

如何使用CSS為選定的列表項賦予不同的顏色?

突出顯示項目onClick-React.js

編輯:

我想突出顯示單擊的內容,並刪除上一個單擊的內容的突出顯示。

我編寫了一種突出顯示列表元素並保持突出顯示的方法,直到您再次單擊它為止:

SegmentsList.js

import React, {Component} from 'react';
import Link from "react-router-dom/es/Link";
import {Button} from 'reactstrap';
import cabeza from '../atlas/json/cabeza.json';
import SegmentsListItem from "./SegmentsListItem";

const parte = getParameterByName('parte') || 0;


export default class SegmentsList extends Component {
    constructor(props) {
        super(props);
    }

    render() {
        console.log(cabeza[parte].etiquetas);
        readTextFile(cabeza[parte].etiquetas);

        function readTextFile(url) {
            const rawFile = new XMLHttpRequest();
            rawFile.open("GET", url, false);
            rawFile.overrideMimeType('text/xml; charset=iso-8859-1');
            rawFile.onreadystatechange = function () {
                if (rawFile.readyState === 4) {
                    const text = rawFile.responseText;
                    // console.log(rawFile.responseText);
                    const lines = splitLines(text);
                    // console.log(lines);
                    const words = splitWords(lines[0]);
                    // console.log(words);
                    window.words = words;
                }
                return;

                function splitLines(text) {
                    return text.split('\n');
                }

                function splitWords(line) {
                    return line.split('" "').slice(1);
                }
            };
            rawFile.send();
        }


        return (
            <div>
                <ol>
                    {window.words.map((word, index) =>
                        <SegmentsListItem word={word} key={index}/>
                    )}
                </ol>

                <Button
                    color='primary'
                    className='mt-3 ml-3'
                >
                    <Link to='/'/>
                    Volver a la portada
                </Button>
            </div>

        );
    }
}

function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}

SegmentsListItem.js

import React, {Component} from 'react';

class SegmentsListItem extends Component {
    constructor(props) {
        super(props);

        this.state = {highlighted: false};

    }

    highlight = (e) => {
        console.log(e.target.className);
        if (!this.state.highlighted) {
            console.log('highlight');
            e.target.className = 'segmentsListSelected';
        } else {
            console.log('remove highlight');
            e.target.className = 'segmentsList';
        }
        this.setState({highlighted: !this.state.highlighted})
    };

    render() {


        return (
            <li
                onClick={this.highlight}
                className='segmentsList'
                key={this.props.index}>{this.props.word}</li>
        );
    };
}

export default SegmentsListItem;

謝謝您的幫助。

您沒有正確使用React,我強烈建議您花一些時間閱讀有關如何使用組件的文檔。 話雖這么說,在這種情況下,您應該使用狀態來存儲加載的單詞,並用於活動選擇。 此外DONT我再說一遍DONT打開渲染方法的文件!...渲染周期可能發生了很多事,就意味着你打開該文件每次渲染發生,這是一個壞主意。

// these are more helper functions.. either define them on your class or just define them in a helpers/utility file. or just put as a global above the class 
function splitLines(text) {
    return text.split('\n');
}

function splitWords(line) {
    return line.split('" "').slice(1);
}

export default class SegmentsList extends Component {
    constructor(props) {
        super(props);
        this.state = { words: [], activeWord: -1 }
    }
    onClickFunction = (idx) => {
        // set the state to only have a current word selection which will unselect the previous selection
        this.setState({activeWord: idx})
    }

    readTextFile = (url) => {
        const rawFile = new XMLHttpRequest();
        rawFile.open("GET", url, false);
        rawFile.overrideMimeType('text/xml; charset=iso-8859-1');
        rawFile.onreadystatechange = () => {
            if (rawFile.readyState === 4) {
                const text = rawFile.responseText;
                const lines = splitLines(text);
                const words = splitWords(lines[0]);
                this.setState({words});
            }
            return;
        };
        rawFile.send();
    }
    componentDidMount() {
        this.readTextFile(cabeza[parte].etiquetas);
    }
    render() {
        return (
            <div>
                <ol>
                    {this.state.words.map((word, index) =>
                        <li
                          onClick={this.onClickFunction.bind(null, index)}
                          className={`segmentsList${this.state.activeWord === index ? ' selected' : ''}`}
                          key={index}
                        >
                          {word}
                        </li>
                    )}
                </ol>

                <Button
                    color='primary'
                    className='mt-3 ml-3'
                >
                    <Link to='/'/>
                    Volver a la portada
                </Button>
            </div>

        );
    }
}

那么最后一件事是在CSS中添加一個用於選擇的類

.segmentsList:hover, .segmentsList.selected {
    background: black;
    color: white;
    cursor: pointer;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM