ReactJS.NET中函数无法触发,如何在render中调用箭头函数?
Hey there! Let's break down why your test arrow function isn't triggering in the CommentBox component's render method, and how to fix it properly.
Why Your Current Approaches Aren't Working
<test />: This syntax tells React to treattestas a React component, not a regular function. Sincetestisn't defined as a component (it doesn't follow React's component rules, like starting with an uppercase letter or returning valid JSX), this won't execute the function at all.{test}: Here you're just passing the function reference to JSX, not actually calling it. React will convert the function object to a string and display it (like() => { ... }) instead of running the code inside.
The Correct Way to Call the Function
To execute your test function inside render, you need to call it explicitly with parentheses: {test()}. But there's one more tweak needed—your function returns an HTML string right now, which React will render as plain text by default. Let's fix that too.
Option 1: Return JSX Instead of a String (Recommended)
Rewrite your test function to return a JSX element instead of an HTML string—this is the standard, safe React approach:
let test = () => { console.log('called!'); return <p>Testing</p>; // No quotes, just native JSX } var CommentBox = React.createClass({ render: function () { return ( <div className="commentBox"> Hello, world! I am a CommentBox. {test()} {/* This executes the function and renders the <p> element */} </div> ); } }); ReactDOM.render( <CommentBox />, document.getElementById('root') // Make sure your HTML has a root element with this ID );
Option 2: Use dangerouslySetInnerHTML (For HTML Strings)
If you have to return an HTML string for some reason, you can use React's dangerouslySetInnerHTML prop to render it as actual HTML. Important: Only use this if you fully trust the source of the HTML, as it can expose your app to XSS vulnerabilities.
let test = () => { console.log('called!'); return "<p>Testing</p>"; } var CommentBox = React.createClass({ render: function () { return ( <div className="commentBox"> Hello, world! I am a CommentBox. <div dangerouslySetInnerHTML={{ __html: test() }} /> </div> ); } });
Quick Side Note
If you ever build a custom React component later on, remember that React requires component names to start with an uppercase letter (like Test instead of test). This helps React tell the difference between built-in HTML elements and your custom components.
内容的提问来源于stack exchange,提问作者Lars Holdgaard

