1
我正在從Freecodecamp實施Markdown預覽器,但我遇到了一些問題。輸入組件上的onChange事件沒有被觸發,我找不到原因!React JS onChange事件未觸發
任何想法?
class MarkDownPreviewer extends React.Component {
constructor(props) {
super(props);
this.state = {
inputText: this.props.text
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
alert("a");
this.setState({inputText: event.target.value});
}
render() {
return (
<div id="wrapper">
<MarkDownInput text={this.state.inputText} onChange={this.handleChange}/>
<MarkDownOutput output={this.state.inputText}/>
</div>
);
}
}
class MarkDownInput extends React.Component {
render() {
return (
<textarea className="input">{this.props.text}</textarea>
);
}
}
class MarkDownOutput extends React.Component {
parseMarkup(rawInput) {
var rawMarkup = marked(rawInput, {gfm: true, sanitize: true});
return {__html: rawMarkup};
}
render() {
return (
<div className="output" dangerouslySetInnerHTML={this.parseMarkup(this.props.output)}>
</div>
);
}
}
var previewText = '# Heading\n\n ## Sub-heading\n \n### Another deeper heading\n \nParagraphs are separated\nby a blank line.\n\nLeave 2 spaces at the end of a line to do a \nline break\n\nText attributes *italic*, **bold**, \n`monospace`, ~~strikethrough~~ .\n\nShopping list:\n\n * apples\n * oranges\n * pears\n\nNumbered list:\n\n 1. apples\n 2. oranges\n 3. pears\n\nThe rain---not the reign---in\nSpain.\n\n *[Herman Fassett](https://freecodecamp.com/hermanfassett)*';
ReactDOM.render(
<MarkDownPreviewer text={previewText} />,
document.getElementById('markpreview')
);
html, body {
height: 100%;
}
#markpreview {
height: 100%;
}
#wrapper {
display:flex;
height: 100%;
}
.input {
width: 50%;
background-color: #e3e3e3;
margin-right: 10px;
padding: 10px;
}
.output {
width: 50%;
background-color: #f3f3f3;
white-space: pre;
padding: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/marked/0.3.5/marked.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="markpreview"></div>
OMG謝謝謝謝!這其實很簡單。再次感謝! – coffeeak
閱讀了Facebook ReactJS的一些文檔後,我發現了有關提升狀態:https://facebook.github.io/react/docs/lifting-state-up.html。對於那些遇到同樣問題的人可能會有所幫助。 – coffeeak