您可以創建一個自定義組件,然後使用該自定義組件爲「」拆分單詞,但我嘗試創建一個不太乾淨的jsfiddle,但顯示了它如何工作的演示。 爲了表示對這個職位代碼:
class Hello extends React.Component {
constructor() {
super();
this.handleClick = this.handleClick.bind(this);
}
split(str) {
return str.split(" ");
}
make(str, i) {
return <span key={i} style={{marginLeft:3}} onClick={this.handleClick}>{str}</span>;
}
handleClick(e) {
console.log(this.props.highlights, e.target.innerText);
if (this.props.highlights.indexOf(e.target.innerText) !== -1) {
e.target.style.background = "red";
}
}
render() {
const parts = this.split(this.props.name);
return <div>{parts.map((d, i) => {
return this.make(d, i);
})}</div>;
}
}
ReactDOM.render(
<Hello highlights={['random', 'paragraph', 'inside']} name="This is a random paragraph with some not so random text inside of this paragraph" />,
document.getElementById('container')
);
僅當您單擊文本時數組纔會填充? _請注意單詞段落在標籤內部兩次,但我只需要突出顯示我點擊的特定單詞_沒有獲得該部分 – Dane
不是。它的預製數組。我需要突出顯示與數組 –
中的某個字符串對應的段落內的文本。在這種情況下,'段落需要突出顯示不是它嗎? – Dane