2
我做了一個小項目來了解更多關於反應的內容,並且注意到當窗口大小發生變化時,視圖響應非常差。爲什麼窗口大小調整時,我的小React項目會非常糟糕?
我覺得我必須做某件事情,我不應該這樣做,這是創造這種繁瑣的經驗。
這裏是我的應用程序:
import ColourCard from "./components/colour-card";
const url = "https://raw.githubusercontent.com/mdn/data/master/css/syntaxes.json";
class App extends React.Component {
constructor() {
super();
this.state = {
error: null,
colours: []
};
}
componentDidMount() {
fetch(url)
.then(response => response.json())
.then(data => {
let colours = data['named-color']['syntax'].split(' | ');
colours = colours.filter((colour) => {
return !colour.includes('gray') && !colour.includes('transparent');
});
this.setState({ colours });
let clipboard = new Clipboard('.js-copy');
clipboard.on('success', function(e) {
const el = e.trigger.closest('.card').parentNode.getElementsByClassName('card-flash')[0];
el.getElementsByTagName('strong')[0].innerHTML = e.text;
el.classList.add('active');
setTimeout(() => el.classList.remove('active'), 1000);
});
})
.catch(e => this.setState({ error: 'Ooops, error' }))
}
render() {
const { error, colours } = this.state;
if (error) {
return <div>{error}</div>
}
if (!colours.length) {
return <div>Loading...</div>
}
return (
<div className="grid">
{colours.map((colour, index) => {
return <ColourCard colour={colour} key={index}></ColourCard>
})}
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById("app"));
和我的繼承人卡組件:
class ColourCard extends React.Component {
render() {
const colour = tinycolor(this.props.colour);
const style = {
backgroundColor: colour.toHexString()
};
return (
<div className="grid__item [email protected] [email protected]">
<div className="card">
<div className="card__colour" style={style}></div>
<div className="card__meta">
<div className="card__meta-item js-copy" data-clipboard-text={this.props.colour}>{this.props.colour}</div>
<div className="card__meta-item js-copy" data-clipboard-text={colour.toHexString()}>{colour.toHexString()}</div>
<div className="card__meta-item js-copy" data-clipboard-text={colour.toRgbString()}>{colour.toRgbString()}</div>
<div className="card__meta-item js-copy" data-clipboard-text={colour.toHslString()}>{colour.toHslString()}</div>
<div className="card__meta-item js-copy" data-clipboard-text={colour.toHsvString()}>{colour.toHsvString()}</div>
</div>
</div>
<div className="card-flash" style={style}>
<span className="card-flash__text">
<strong className="card-flash__strong"></strong>
<br />
Copied!
</span>
</div>
</div>
);
}
}
export default ColourCard;
https://codepen.io/matt3224/project/editor/ZvLGGA#
任何幫助,非常感謝!
我明白了,我怎麼做我想通過反應做什麼?而不是我上面的那個 – matt3224
你需要使用你的狀態和你的jsx。例如,這行'el.classList.add('active')' - 你應該做的是修改你的狀態,然後讓你的jsx監聽它的'className' - 就像'className = { this.state.active? 'active':''}' –
我只是爲了測試,評論了違規代碼,但它仍然相當滯後。我做錯了什麼嗎? https://71b39fcefff9415289c6746d496a64b3.codepen.website – matt3224